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

Steven D'Aprano steve+comp.lang.python at
Tue Aug 23 11:25:06 EDT 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:

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

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


More information about the Python-list mailing list