How to Read a File Line by Line in Python

09/10/2021

Contents

In this article, you will learn how to read a file line by line in Python.

Read a File Line by Line

There are several ways to read a file line by line in Python, and some of the most common ones are:

Using a for loop

This is a simple and straightforward method to read a file line by line. The file is opened using the open() function, and then each line of the file is processed in the for loop. In this case, the file object is treated as an iterable, with each iteration of the loop representing a line of the file. This method is efficient for reading large files because it only loads one line of the file into memory at a time.

with open("filename.txt") as file:
    for line in file:
        print(line)

Using the readline() method

This method reads a single line of the file at a time and returns it as a string. You can use a while loop to read the file line by line, with the readline() method being called on each iteration of the loop. The loop continues until readline() returns an empty string, which indicates that the end of the file has been reached.

with open("filename.txt") as file:
    line = file.readline()
    while line:
        print(line)
        line = file.readline()

Using the readlines() method

The readlines() method reads all the lines of the file at once and returns them as a list of strings, with each string representing a line of the file. While this method is convenient, it can use a lot of memory if the file is very large, as it loads the entire contents of the file into memory.

with open("filename.txt") as file:
    lines = file.readlines()
    for line in lines:
        print(line)

It’s important to use the with statement when opening files, as it ensures that the file is properly closed after it’s been read, even if an exception is raised during the processing of the file.