What's the best way to read a text-file line by line


In the book LPTHW I read the lessons refering to open and read (text)-files.
I think I understood the difference between file.read() and file.readline().
But my question is what is the best way to read all lines from a text-file in python?

1.) readline and while-loop

f = open(‘test.txt’)
line = f.readline()
while line:
line = f.readline()

2.) readlines and for-loop

f = open(‘test.txt’)
lines = f.readlines()
for line in lines:

3.) for … in construction

f = open(‘test.txt’)
for line in f:

thanks in advice

BR Johann

hello zed
can you pls answer my question? → What’s the best way to read a text-file line by line
BR James

Remember there is also ‘readlines’ which seems to be what you are after.


# open the file
file = open("example.txt")
# read the file as a list
data = file.readlines()
# close the file


Hallo gpkesley.

thank you for your answer!

But, did you also see my first post?

BR James

I’m not sure I understand @james63 Do you mean which is the most efficient implementation? Or how does readlines() work in python.

Take a look at how it’s implemented in code and it might answer your question, I.e. how did the Python Team implement it…

Hello @gpkesley.

I wanted to know which version ( 1 ,2 ,3) would be used in common.
And if there is a reason why this version is used oftener as the other versions.


Do you mean, take a text file, but only print one line at a time? Can you supply a use case to help understand?

People don’t tend to loop over text one line at a time.And without any waits it will print too screen so quick that it will seem like a block anyway won’t it?

You are right, only to print the line to screen doesn’t make sense.
But, the call of print was only the prove that I’am able to to step through the file line by line.

Instead of print I want to

I ) extract coordinates from a nmea (GPS) file :

II ) store and visualize the values from my cardio-bike
08.4 1h 1101cal 37.0km
09.4 1h 1048cal 37.0km
10.4 1h 1177cal 37.0km
11.4 1h 1144cal 37.9km

III ) …

Therefore I want to have access to lines.

BR James