Javaexercise.com

How to Read a File Line by Line in Python?

To read a file line by line in Python, we can use either readline() or readlines() method. The readline() method reads a single line of a file whereas readlines() method returns a list of all lines of the file.

In this article, we will use mainly use these two methods.

Let's get started with examples.

Read File Line by Line using readlines() Method

This example uses readlines() method to read file line by line and then rstrip() method is used to remove all the \n characters from the end of each line. See the code example below.

"""
How to read a file line by line in Python
"""
filename = "myfile.txt"
with open(filename) as file:
    all_lines = file.readlines()
    all_lines = [line.rstrip() for line in all_lines]
  
print(all_lines)

 

Read File Line by Line using readline() Method

Here, we used readline() method that reads only a single line of the file. So, we used it with a loop to read all the lines of the file. 

"""
How to read a file line by line in Python
"""
filename = "myfile.txt"
with open(filename) as file:
    while (line := file.readline().rstrip()):
        print(line)

 

Read File Line by Line using readline() and encoding

While reading a file, we must specify read mode and encoding type. The UTF-8 is a default encoding while reading the file, but you can specify if the type is other than UTF-8. See the code example below. 

"""
How to read a file line by line in Python
"""
filename = "myfile.txt"
with open(filename, 'r', encoding='UTF-8') as file:
    while (line := file.readline().rstrip()):
        print(line)

 

Read File Line by Line using loop and append() Method

If you don't want to use built-in methods such as readline() or readlines() then use this code that uses a loop and append() method to iterate and append each line of the file into a list. See the code below.

"""
How to read a file line by line in Python
"""
filename = "myfile.txt"
with open(filename) as file:
    lines = []
    for line in file:
        lines.append(line)
print(lines)

 

Read File Line by Line using List comprehension

This is a short and concise solution to read a file. Here, the list comprehension concept is used to get a list of all the lines of the file. See the below Python code.

"""
How to read a file line by line in Python
"""
filename = "myfile.txt"
all_lines = [line.rstrip("\n") for line in open(filename)]
print(all_lines)

 

 

Useful Resources: