an ugly file-reading pattern

djw dwelch91 at attbi.com
Sat Apr 12 23:01:11 EDT 2003


Istvan Albert wrote:

> 
> I have been working with perl and java for quite a
> few years now and I am currently actively looking
> to replace perl wit something better, a language that
> promotes software engineering principles. I was
> directed toward python and ruby, I have been
> working with both of them for a couple of weeks now.
> 
> And now for the python question:
> 
> Suppose that I'm looking for a way to
> read lines from a text file:
> 
> 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,
> 
> cheers,
> 
> Istvan.

I recommend that you put down the (outdated) "Learning Python" book and pick 
up the (new) "Python Cookbook". 

A more recent (Python 2.2+ish) way of doing this task is:

for line in open('filename'):
        print line 

See section 4.1 in "Python Cookbook" for more info.

/djw/




More information about the Python-list mailing list