Python Program to read the contents of a file


April 1, 2022, Learn eTutorial
1204

In this simple python program, we need to read the contents of a file. It is a number-based python program.

For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:

What is a file in python?

In this file python program, we need to know about the files. Files are used as locations that are named to store permanently certain related data in a hard disk. We know that random access memory (RAM) is a volatile memory in which all the data inside the RAM will be deleted when the power goes off. So we need some method to store our data in a nonvolatile memory, which is a Hard disk, that is the Files.

What are the basic operations on a file in python?

We need some basic operations to save the data in the files. That is,

  • Open a File
  • Read/Write in a File (operations on file)
  • Close the File

Files can be opened by the inbuilt function, which is open() that returns a file object, used for reading and writing the file. Also, for closing the file, we use the close() function, which will free all the memory and resources which is used by the file. Python has an inbuilt garbage collector to perform that function. But we didn't use that to free up the resources. For reading, we have to open the file in reading mode, and we have a lot of methods to read a file. Similarly, for writing a file, we need to open the file in write mode.

How to read the file content in python?

In this File python program, we need to accept a string as a file name with .txt extension, and then we open the file using the open() in read mode. Now use the readline function to read the first line of the file and save that to a variable. Now open a while loop to print all the remaining lines of the file and print all the lines using the print function. Then close the file using the close() function.

ALGORITHM

STEP 1: Accept the file name in text format and save that in a variable.

STEP 2: Open the file in read mode and save that in a variable.

STEP 3: Read the file first line using the readline method.

STEP 4: Use a while loop to read and print the other lines of the file.

STEP 5: Print the first line and close the file using close in python language.

Python Source Code

                                          a=str(input("Enter the file with .txt:"))
file2=open(a,'r')
line=file2.readline()
while(line!=""):
    print(line)
    line=file2.readline()
file2.close()
                                      

OUTPUT

Contents of file: 
Python Programming
 
Output: 
Enter the file with .txt: data2.txt
Python Programming.