Simple looping question...

Fredrik Lundh fredrik at pythonware.com
Tue Apr 3 03:37:27 EDT 2001


David Allen wrote:
> for line in file.readlines():
>   print line
>
> There, python has two choices.

python methods usually don't have "context dependent"
behaviour, and readlines is no exception.  it's defined to
return a real list object, and always does.

> I don't have code proof for that - it's just that
> I've run a program that uses that type of a construct:
>
> for line in file.readlines():
>   # Do something with line
>
> in several programs that get fed 80MB data files,
> and I've never noticed python's memory usage
> encompassing 80 MB, which is what you would expect
> if the interpreter actually allocated an array to
> keep the whole file in memory.

looks like your computer is too fast for you ;-)

to get the behaviour you'd hoped for, you can use xreadlines
instead of readlines (2.1 only).

Cheers /F





More information about the Python-list mailing list