2

I'm doing some I/O with Python 3 and noticed this:

fname = 'mbox.txt'
fh = open(fname)

sum( 1 for line in fh) # count lines
# Out[49]: 132045
sum( 1 for line in fh)
# Out[50]: 0

mbox.txt is here, which should be trivial.

Does it mean the file object fh expires after being used once? I read the documentation and didn't get it.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
YJZ
  • 3,934
  • 11
  • 43
  • 67

1 Answers1

4

If you iterate the file object, current file position is advanced. Once it reach the end of the file, reading file will return empty string.

To reset the file position, you can use seek method:

sum( 1 for line in fh)
fh.seek(0)  # Move file position/pointer to the beginning (0).
sum( 1 for line in fh)
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • But note that this will only work for certain types of input streams. It will not work for things like pipes or interactive input. – Tom Karzes Feb 20 '16 at 08:43
  • thanks @falsetru so I understand `fh` is like a pointer/iterator – YJZ Feb 21 '16 at 08:09