Rich
Rich

Reputation: 1851

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

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.

Upvotes: 4

Views: 16902

Answers (2)

user2555451
user2555451

Reputation:

One very simple solution is to set a flag:

eof = False
for line in file:
    #do stuff
    if something:
        break
else:
    eof = True

In the end, if eof is True, it means you hit the end of the file. Otherwise, there are still some lines.

What's important here is the for...else construct. The else-block will only be run if the for-loop runs through without hitting a break.

Upvotes: 0

dm03514
dm03514

Reputation: 55962

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

Upvotes: 15

Related Questions