an ugly file-reading pattern
Andrew Dalke
adalke at mindspring.com
Sun Apr 13 19:20:47 EDT 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:
break
for line in lines:
do_stuff()
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.
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list