4

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.

Community
  • 1
  • 1
Rich
  • 1,669
  • 2
  • 19
  • 32
  • 1
    the somewhat-rarely used `for/else`. Which should have been named `for/nobreak`, but that's a different discussion. – roippi Nov 04 '13 at 22:22
  • Iterating over a file causes python to buffer the file in memory which leads to [somewhat unexpected behavior when you call `f.tell()`.](http://stackoverflow.com/questions/14145082/file-tell-inconsistency) – Bi Rico Nov 04 '13 at 22:26

2 Answers2

15

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

dm03514
  • 54,664
  • 18
  • 108
  • 145
0

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.