[Tutor] New to this

Alan Gauld alan.gauld at btinternet.com
Mon Jun 21 01:19:51 CEST 2010


"Neil Thorman" <neil.thorman at gmail.com> wrote 

>>>>inp = file("menu.txt", "r")
> *What is inp? What does it now contain?*
>>>>print inp.readlines()
> ['spam & eggs\n', 'spam & chips\n', 'spam & spam']
> 
> but if I do it again I get:
>>>> print inp.readlines()
> []
> 
> I'm baffled, why is inp now empty?

OK, I've been asked thios before so I guess I need to add an 
explanation to the tutor!

When you work with  files its like using a cursor to indicate 
where you are in the file. When you firwst open the file the 
cursor is at the beginning of the file. As you read content the 
cursor moves through the file. If you use teadlines() you read 
the whole file in so that the cursor is at the end of the file. 
If you try calling readlines again there is no more data to 
read so you get an empty list.

You can reset the cursor using the seek() method

inp.seek(0)

Now readlines() will return the data again.

I'll try to write that up a bit more clearly and add it to the files 
topic.

HTH<


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list