Methods on file-like objects can only used once on one object?

darnold darnold992000 at yahoo.com
Tue Aug 23 17:24:11 CEST 2011


On Aug 23, 9:21 am, Yingjie Lin <Yingjie.... at mssm.edu> wrote:
> Hi Python users,
>
> I just realize that my post yesterday shouldn't be specifically for mechanize. It should be a general question for file-like objects.
>
> >>> f = open('my_file.txt')
> >>> print f.readlines()
>
>         ( prints a list of strings>>> print f.readlines()
>
> []
>
> There are quite a few methods for file-like objects that can only be used once on one object. If I prefer to use some of these methods on one object, one after another, like:
>
> f.readlines()
> f.read()
> ...
>
> What should I do? Thank you.
>
> - Yingjie

Each of those calls consumes the entire file, leaving the file pointer
at end-of-file. to reset the file pointer back to the beginning of the
file and enable re-reading, use f.seek(0) .



More information about the Python-list mailing list