Open In App

Read a file line by line in Python

Last Updated : 21 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Python provides built-in functions for creating, writing, and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary language, 0s, and 1s). In this article, we are going to study reading line by line from a file.

Example:

Python
with open('filename.txt', 'r') as file:
    for line in file:
        print(line.strip())

Using Loop

An iterable object is returned by open() function while opening a file. This final way of reading a file line-by-line includes iterating over a file object in a loop. In doing this we are taking advantage of a built-in Python function that allows us to iterate over the file object implicitly using a for loop in combination with using the iterable object.

Python
L = ["Geeks\n", "for\n", "Geeks\n"]

file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()

file1 = open('myfile.txt', 'r')
count = 0

print("Using for loop")
for line in file1:
    count += 1
    print("Line{}: {}".format(count, line.strip()))

file1.close()

Output

Using for loop
Line1: Geeks
Line2: for
Line3: Geeks

Using List Comprehension

A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. Here, we will read the text file and print the raw data including the new line character in another output we removed all the new line characters from the list.

Python
with open('myfile.txt') as f:
    l = [line for line in f]

print(l)

with open('myfile.txt') as f:
    l = [line.rstrip() for line in f]

print(l)

Output:

['Geeks\n', 'For\n', 'Geeks']
['Geeks', 'For', 'Geeks']

Using readlines()

Python readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines. We can iterate over the list and strip the newline '\n' character using strip() function.

Python
L = ["Geeks\n", "for\n", "Geeks\n"]

file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()

file1 = open('myfile.txt', 'r')
Lines = file1.readlines()

count = 0
for line in Lines:
    count += 1
    print("Line{}: {}".format(count, line.strip()))

Output

Line1: Geeks
Line2: for
Line3: Geeks

Python With Statement

When working with files in Python, it is important to close the file after operations to avoid bugs such as unsaved changes or resource leaks. Normally, you would need to explicitly call file.close() after opening a file.

However, using the with statement simplifies this process. It automatically handles opening and closing the file for you, ensuring the file is properly closed as soon as the code block inside the with statement finishes execution even if an error occurs. This eliminates the need to manually close the file and results in cleaner, safer code.

Python
L = ["Geeks\n", "for\n", "Geeks\n"]

with open("myfile.txt", "w") as fp:
    fp.writelines(L)

count = 0
print("Using readlines()")

with open("myfile.txt") as fp:
    l = fp.readlines()
    for line in l:
        count += 1
        print("Line{}: {}".format(count, line.strip()))

count = 0
print("\nUsing readline()")

with open("myfile.txt") as fp:
    while True:
        count += 1
        line = fp.readline()

        if not line:
            break
        print("Line{}: {}".format(count, line.strip()))

count = 0
print("\nUsing for loop")

with open("myfile.txt") as fp:
    for line in fp:
        count += 1
        print("Line{}: {}".format(count, line.strip()))

Output

Using readlines()
Line1: Geeks
Line2: for
Line3: Geeks

Using readline()
Line1: Geeks
Line2: for
Line3: Geeks

Using for loop
Line1: Geeks
Line2: for
Line3: Geeks

Next Article
Article Tags :
Practice Tags :

Similar Reads