This is a Python Program to read the contents of a file.
The program takes the file name from the user and reads the contents of that file.
1. Take the file name from the user.
2. Use readline() function for the first line first.
3. Use a while loop to print the first line and then read the remaining lines and print it till the end of file.
4. Exit.
Here is source code of the Python Program to read the contents of a file. The program output is also shown below.
a=str(input("Enter the name of the file with .txt extension:")) file2=open(a,'r') line=file2.readline() while(line!=""): print(line) line=file2.readline() file2.close()
1. User must enter a file name.
2. The file is opened using the open() function in the read mode.
3.The readline() outside the while loop is used to read the first line of the file.
4. Inside the loop, the first line is first printed and then the remaining lines are read and subsequently printed.
5. This continues this the end of file.
6. The file is then closed.
Case 1: Contents of file: Hello world Output: Enter the name of the file with .txt extension: data1.txt Case 2: Contents of file: This programming language is Python. Output: Enter the name of the file with .txt extension: data2.txt This programming language is Python.
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Check Python Books
- Practice Programming MCQs
- Apply for Programming Internship
- Apply for Python Internship
- Check Information Technology Books