I know to iterate a file line by line, I can use construct like this:
for line in file:
do stuff
But if I also have a break statement somewhere inside the for, once I am out of the for block, how do I tell if it is the break that take me out of the for construct OR it is the because I hit the end of file already?
I tried the suggestion from How to find out whether a file is at its `eof`?:
f.tell() == os.fstat(f.fileno()).st_size
But that doesn't seem to work on my Windows machine. Basically, f.tell() always returns the size of the file.
you could use for..else
for line in f:
if bar(line):
break
else:
# will only be called if for loop terminates (all lines read)
baz()
source
the else suite is executed after the for, but only if the for terminates normally (not by a break).
Ned Batchelder's article about for..else
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With