Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The python file object has an iterator interface (rather than a list-like one). When you loop over it, you consume the lines one by one. Hence, after evaluating the second cell, the file descriptor f is at the end of the file. Looping again will yield nothing.

Consider this example:

sage: f = open('example.txt')
sage: f.tell()           # tells at what position we are in the file
0
sage: for s in f: pass   # loop over f, doing nothing
sage: f.tell()
10
sage: f.next()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
...
sage: f.seek(0)        # rewind to start
sage: f.readline()     # read one line
'exampleexampleexample\n'