Python provides different ways in order to read a file line by line. Event binary files can be read with python the most popular usage is reading text or ASCII files to read line by line. In this tutorial, we examine different methods and ways to read a file line by line in Python.
Read File Line By Line using readline() Method
The file object provides readline()
method in order to read a single line from the opened file and returns this line as a return value. The readline() method starts reading from the start of the line to the end of the line. The readline() method can be used to read a single line and iterate over all lines by using while
loop.
f = open ("db.txt","r")
while True:
line = f.readline()
if not line:
break
print(line)
f.close()
Read File Line By Line using readlines() Method
The readlines() method is also provided by the file object. So after opening a file the readlines() method can be used to read all lines. The readlines() method returns all lines as a list. Every line is an item in the returned list. The list can be iterated by using for loop.
f = open ("db.txt","r")
lines = f.readlines()
for line in lines:
print(line)
f.close()
Read File Line By Line using for Loop
Python provides magical ways to use loops. The for loop can be used to read an opened file object line by line. The file object is provided to the for loop and iterated in every line for each step.
f = open ("db.txt","r")
for line in f:
print(line)
f.close()
Read File Line By Line using with Statement
Another pythonic way to read a file line by line is using the with
statement. In the previous examples, the file is opened as the first step and after reading the file it should be closed. But by using the with the statement the file close is done implicitly which prevents errors and bugs.
with open ("db.txt","r") as f:
while True:
line=f.readline()
if not line:
break
print(line)