Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect end of file in Python after iterating the file object with "for" statement

Tags:

python

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.

like image 996
Rich Avatar asked Dec 07 '22 04:12

Rich


1 Answers

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

like image 53
dm03514 Avatar answered May 13 '23 14:05

dm03514