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

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Aug 23 17:25:06 CEST 2011


Yingjie Lin 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()
> []

Once you've read the file, the file pointer is now at the end of the file.
To go back to the beginning of the file and read it again, you have to use
the seek method:

f.seek(0)

But better is to not read the file twice:


f = open('my_file.txt')
lines = f.readlines()
print lines
print lines
print lines
print lines
f.close()

There's no need to read the lines again unless you expect that the file has
changed.


-- 
Steven




More information about the Python-list mailing list