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()
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