Reading a file line by line is a common file-handling operation. It allows us to process each line individually without loading the entire file into memory, making it efficient for both small and large files.
with open('filename.txt', 'r') as file:
for line in file:
print(line.strip())
Python provides multiple ways to read files line by line depending on the use case.
Using with Statement
Here, the file is opened using the with statement and each line is read one at a time using a for loop. The loop automatically moves through the file until all lines have been processed.
L = ["Geeks\n", "for\n", "Geeks\n"]
with open("myfile.txt", "w") as fp:
fp.writelines(L)
count = 0
with open("myfile.txt", "r") as fp:
for line in fp:
count += 1
print("Line{}: {}".format(count, line.strip()))
Output
Line1: Geeks
Line2: for
Line3: Geeks
Explanation: file is opened using the with statement, which automatically closes it after use. The for loop reads one line at a time and strip() removes the newline character before printing.
Using for Loop
A file object can be directly iterated using a for loop. Each iteration reads the next line from the file, allowing the contents to be processed line by line.
L = ["Geeks\n", "for\n", "Geeks\n"]
file1 = open('myfile.txt', 'w')
file1.writelines(L)
file1.close()
file1 = open('myfile.txt', 'r')
count = 0
for line in file1:
count += 1
print("Line{}: {}".format(count, line.strip()))
file1.close()
Output
Line1: Geeks
Line2: for
Line3: Geeks
Explanation: for loop iterates through each line in the file. Since only one line is processed at a time, this method is efficient even for large files.
Using readlines()
The readlines() method reads all lines from the file and stores them in a list. We can then iterate through the list and access each line individually.
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
Explanation: readlines() returns a list containing all lines of the file. We then iterate through the list and print each line after removing the newline character.
Using List Comprehension
List comprehension reads lines from the file and stores them in a list in a single statement. Each line becomes an element of the list, which can then be processed or displayed as needed.
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']
Explanation: first list comprehension stores the lines exactly as they appear in the file, including newline characters. The second uses rstrip() to remove trailing newline characters before storing the lines in the list.