"Neil Thorman" <neil.thor...@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/


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to