[Tutor] New to this

Adam Bark adam.jtm30 at gmail.com
Mon Jun 21 01:10:40 CEST 2010


On 20 June 2010 19:38, Neil Thorman <neil.thorman at gmail.com> wrote:

> I'm picking this up as a hobby really, not having done any programming
> since Acorn I'm pretty much starting form scratch (and even back in the
> BASIC day I never really got to grips with files).
> This is from Alan Gauld's Learning to Program: Handling Files.
> http://www.freenetpages.co.uk/hp/alan.gauld/
>
> <http://www.freenetpages.co.uk/hp/alan.gauld/>Can I just check I'm getting
> it?
>
>
> *Menu.txt contains*
>
> *Spam & Eggs*
> *Spam & Chips*
> *Spam & Spam*
>
> >>>inp = file("menu.txt", "r")
> *What is inp? What does it now contain?*
> *The following creates a list;*
>

inp is a file object.


> *
> *
> *
> >>>print inp.readlines()
> ['spam & eggs\n', 'spam & chips\n', 'spam & spam']
>
> *
>

readlines is a method of inp. It's basically a function that works
specifically on that object, in this case it reads each line from the file
and puts it into a list and then returns it; the shell then prints it out.


> *
> but if I do it again I get:
> >>> print inp.readlines()
> []
>
> *
>

At this point you have reached the end of the file so there are no more
lines to read, if you just want one line at a time then you should use
inp.read()


> *
> I'm baffled, why is inp now empty?
> *
>

inp isn't really empty it's still a file object there is just no data left
to read.


> *
>
> Many thanks
>
> Neil
>
> ps. I'm working in the IDLE Python Shell.
> *
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100621/9fa9b472/attachment.html>


More information about the Tutor mailing list