How to read complete text file line by line using Python?


Python has built in file creation, writing, and reading capabilities. In Python, there are two sorts of files that can be handled: text files and binary files (written in binary language, 0s, and 1s).

Let us understand how to open a file in python. Python is a good general purpose programming language that has a lot of helpful file IO functions and modules in its standard library.

You can use the built-in open() function to open a file object for either reading or writing. You can use it to open a file in the following way.

Syntax

The syntax for the open() method is shown below.

File = open(“txt_file_name” ,”access_mode”)

There are 6 access modes in python which are ‘r’, ‘r+’, ‘w’, ‘w+’, ‘a’, and ‘a+’. They are explained below.

  • Read Only ('r') − This mode is used to open a text file for reading.

  • Read and Write ('r+') − This mode allows you to read and write to a file.

  • Write Only ('w') − This mode allows you to write to a file.

  • Write and Read ('w+') − This mode allows you to read and write to a file.

  • Append Only ('a') − This mode allows you to write to a file.

  • Append and Read ('a+') − This mode allows you to read and write to a file.

In this article, we'll look at how to read a file line by line.

Example

The following is an example to open a file named example.txt in read mode.

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

Output

On executing the above program, the following output is generated.

The file example.txt is opened in read mode.

Using readline() method

The readline() method is used to read a file line by line in Python.

Example

Following is an example where the readline() method is used which reads a single line and requires us to use and increment a counter. This code sample opens a file object whose reference is kept in fp, then calls readline() on that file object iteratively in a while loop to read in a line one at a time. The line is then printed to the console.

#python program to read a file line by line using readline()
file = 'example.txt'
#Opening a file whose reference is stored in fp
with open(file) as fp:
   line = fp.readline()
   cnt = 1
   while line:
#pritning the content as it reads line by line        
      print("Line {}: {}".format(cnt, line.strip()))
      line = fp.readline()
      cnt += 1

Output

On executing the above program, the following output is generated.

Using readlines() method

The readlines() method is used to read all of the lines at once and return each line as a string element in a list. This function is useful for small files since it reads the entire file content into memory and then splits it into lines. Using the strip() function, we can loop over the list and remove the newline '\n' character.

Example 1

The following is a python program which reads a file line by line using the readlines() method. The file named example.txt is opened in read only mode using the open() function. Then, using the readlines() method, the lines of the file are printed as output.

#python program to read a file line by line using readlines()
#Opening a file win read access mode
file = open("example.txt","r")
#printing the lines of the file using readlines()
print(file.readlines())

Output

On executing the above program, the following output is generated.

Example 2

The readlines() method reads every line and puts it in a list. We can then iterate over that list and create an index for each line using enumerate().

file = open('example.txt', 'r')
fileContent= file.readlines()

for index, line in enumerate(fileContent):
   print("Line {}: {}".format(index, line.strip()))
file.close()

Output

On executing the above program, the following output is generated.

Updated on: 11-May-2023

594 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements