Open In App

Read a file line by line in Python

Last Updated : 02 Jan, 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
# Open the file in read mode
with open('filename.txt', 'r') as file:
    # Read each line in the file
    for line in file:
        # Print each line
        print(line.strip())

Read a File Line by Line 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"]

# Writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()

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

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

# Closing files
file1.close()

Output:

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

Read a File Line by Line 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:
    lines = [line for line in f]

print(lines)

# removing the new line characters
with open('myfile.txt') as f:
    lines = [line.rstrip() for line in f]

print(lines)

Output:

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

Read a File Line by Line 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"]

# writing to file
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()

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

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

Output:

Line1: Geeks
Line2: for
Line3: Geeks

Python With Statement

Using Python With statement, the file must be explicitly closed, and forgetting to do so can cause bugs, as changes may not take effect. To prevent this, the with statement can be used. It simplifies resource management like file streams, ensuring proper handling and making the code cleaner by automatically closing the file, without needing file.close().

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

# Writing to file
with open("myfile.txt", "w") as fp:
    fp.writelines(L)

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

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

# Using readline()
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()))

# Using for loop
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