by BehindJava

Write a program to Read the Contents of a File in Python

Home » python » Write a program to Read the Contents of a File in Python

In this tuturial we are going to learn about reading the Contents of a File in Python.

Python Program to Read the Contents of a File

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

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.
  3. Inside the loop, the first line is first printed, and then the remaining lines are read and subsequently printed.
  4. This continues this the end of file.
  5. The file is then closed.