an ugly file-reading pattern

Donnal Walter donnal at donnal.net
Sat Apr 12 22:32:19 EDT 2003


Istvan Albert wrote:
> now there is the readlines() method
> that slurps everything up (no good for me
> since I don't like to build into my systems
> implicit assumptions about filesizes)
> 
> if I choose to process the file line by line
> the "Learning Python" book advises me to use the
> following atrocity:
> 
> while 1:
>     line = file.readline()
>     if not line: break
> 
> Maybe I'm picky here but having to start an infinite loop
> then needing a conditional to  break out of it is
> anything but an elegant pattern.
> 
> This has left me wondering about python,

In Python 2.2 or later, I believe the following will work:

for line in file:
     print line


Donnal Walter
Arkansas Children's Hospital







More information about the Python-list mailing list