How To Read File Content In Python

Author: Neeraj Avinash

File handling in Python is a part of standard Python installation. Python has built in function to 

  • Create a file
  • Write to file
  • Read the file

Code below demonstrates how we can read the file contents.

''' Program to read the file content ''' 
# Open file in read mode 
f = open("file.txt", "r") 
# Iterate through file object 
for line in f:     
	print(line) 
	
# Close file
f.close()

Lets understand the program

In order to read the file we need to follow these steps:

1. Open the File

Before reading the file, we first need to open the file.

With this code block we open the file in read mode

f = open("file.txt", "r")

With this statement we are opening the file named as “file.txt” available in the current directory and assigned the file handle to variable f

2. Read the file

Once file is opened and the file object is assigned to variable f, now we can iterate through the lines pointed by the file object.

We will use for loop to iterate through the lines in file.

for line in f:
   print(line)
Here we are iterating through the file object and printing each line in the file.

3. Close the file

After reading the file we will close the file with close method of file object.

f.close()

Close function is required to free up the memory used by the file operation. As a best practice we must close the file after performing file operation.

Use of with statement

Python provides a shorter and cleaner way to open the file using with statement

with open filename as file:

With with statement , there is no need to close the file. With statement does required cleanup automatically and frees up memory and resources.

The above program can be written in more cleaner way using with statement 

with open("file.txt", "r") as f:
   for line in f:
       print(line)

 

Last Updated - Sept. 20, 2024
  • Become Instructor

    Start helping millions of people

    Join Now
  • Start Learning

    Start Learning with ease

    Join Now

Connect With Us