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

Hello,

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:
print(line.strip())
line = f.readline()
f.close()

2.) readlines and for-loop

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

3.) for … in construction

f = open(‘test.txt’)
for line in f:
print(line.strip())
file.close()

thanks in advice

BR Johann

@zedshaw
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.

Try:

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

print(data)

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.

BR J

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 :
$GPGGA,181908.00,3404.7041778,N,07044.3966270,
W,4,13,1.00,495.144,M,29.200,M,0.10,0000*40

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