Python Program to Read the Contents of the File

This is a Python Program to read the contents of a file.

Problem Description

The program takes the file name from the user and reads the contents of that file.

Problem Solution

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.

Program/Source Code

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()
Program Explanation

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.

advertisement
advertisement
Runtime Test Cases
 
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.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.