Read File Line By Line In Python

This tutorial will be focussed to discuss three different techniques for how to read file line by line in python. so without wasting any time let’s get started.

1. By Using readlines()

In the below code, we will use readlines() method on file object to obtain the list of all lines of file. Here is the algorithm.

  • We first use the context manager to open the text file in the read mode.
  • Then we call the readlines() method on file object to get the list of all lines.
  • Then we iterate through the list and print the line on this console after removing the last newline character.
#python read file line by line
file_name = "data.txt" # name of the file where data is stored.

# open the file in read mode
with open(file_name,"r") as file:
    lines = file.readlines() # Grab the list of all lines

    for i in lines: # iterate through all lines
        stripped_line = i.strip() # Remove the last new line character
        print(stripped_line)

Save and run the above code. you should see the content of the file get printed on the console.

Output:

Program to read file line by line in python

2. By Using While-Loop

In the following code snippet, we will use a while-loop to read file line by line in python. Here is the algorithm.

  • First, we open the text file in the read-mode.
  • Then we run the infinite while loop.
  • Then on each iteration of the while loop, we grab the next line by calling the readline() method on the file object.
  • Then we check if we reached the end of the file then break the while loop.
  • Else print the line on the console after removing the last newline character.
# Program to read file line by line in python by using while loop
file_name = "data.txt" # name of the file where data is stored.

# open the file in read mode
with open(file_name,"r") as file:
    while True: # run the infinite while loop
        # Read the line
        line = file.readline()
        if not line: # If we reached end of file then exit the loop
            break
        #print the line by removing last newline character
        print(line.strip())

3. Without Using With Statement

In this code example, we obtain the exact output without using context manager.

# Program to read file line by line in python
file_name = "data.txt" # name of the file where data is stored.

# open the file in read mode
file = open(file_name,"r")
lines = file.readlines() # Grab the list of all lines

for i in lines: # iterate through all lines
    stripped_line = i.strip() # Remove the last new line character
    print(stripped_line)

file.close() # close the file

That’s wrap for the tutorial on how to read file line by line in python.

Also read about how to write line to a file in python

Leave a Reply