Difference between readlines() and iterating on a file object?

Duncan Booth duncan.booth at invalid.invalid
Fri Aug 13 11:01:01 EDT 2004


"Richard" <richardd at hmgcc.gov.uk> wrote in
news:411cd102$1 at mail.hmgcc.gov.uk: 

> Hi,
> 
> Can anyone tell me what the difference is between
> 
> for line in file.readlines( ):

reads the entire file into memory and splits it up into a list of lines 
then iterates over the list. If you break from the loop, tough you've lost 
any lines that were read but you didn't handle.

> 
> and
> 
> for line in file:

reads part of the file and strips off one line at a time. Never creates a 
list. Reads more only when it runs out of the block it read. If you break 
from the loop you can do another 'for line in file' and get the remaining 
lines.

> 
> where file is a file object returned from an open( ) call?
> 



More information about the Python-list mailing list