an ugly file-reading pattern

Andrew Dalke adalke at
Mon Apr 14 01:20:47 CEST 2003

Grzegorz Adam Hankiewicz
> 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.

The fastest implementation to work across all versions of
Python since .. 1.3?  Or perhaps 1.4 ... is

while 1:
    lines = file.readlines(100000)
    if not lines:
    for line in lines:

One line longer, faster, doesn't have the "if you happen to
forget the last line of the loop" problem (which is more likely
then forgetting the "if not lines: break" lines).

But seriously, upgrade.

                    dalke at

More information about the Python-list mailing list