Ask Your Question
0

Sometimes there is no any output from text file.

asked 2013-10-09 08:35:58 +0100

AndreWin gravatar image

updated 2013-10-09 08:37:00 +0100

Hello!
Please explain me this code in Sage Notebook:
Cell 1:

f = open('/home/andrei/Docs/1.html')

Cell 2:

for s in f: print(s)

I type the code in cell 1 then in cell 2. First I press shift+enter in cell 1 then in cell 2. My code works fine. Then I press shift+enter in cell 2 - there is no any output. If after that I press shift+enter in cell 1 and then in cell 2 -- my code works again. Why?
Thanks a lot!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2013-10-09 09:52:46 +0100

Luca gravatar image

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'
edit flag offensive delete link more

Comments

Luca, thanks a lot!

AndreWin gravatar imageAndreWin ( 2013-10-19 07:26:56 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2013-10-09 08:35:58 +0100

Seen: 356 times

Last updated: Oct 09 '13