an ugly file-reading pattern

Grzegorz Adam Hankiewicz gradha at titanium.sabren.com
Sun Apr 13 15:23:42 EDT 2003


On 2003-04-13, Istvan Albert <ialbert at mailblocks.com> wrote:
> 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.

An idiom I prefer over that which works with every python version:

        line = file.readline()
        while line:
                do_stuff()
                line = file.readline()

But it also makes for an infinite loop if you happen to forget the
last line of the loop. Life is tough, you have to accept that or
move to newer python versions, as suggested.

-- 
 Please don't send me private copies of your public answers. Thanks.





More information about the Python-list mailing list