an ugly file-reading pattern
Greg Krohn ('rot-13')
'tert at pncen.hf'.decode
Sat Apr 12 23:00:43 EDT 2003
"Istvan Albert" <ialbert at mailblocks.com> wrote in message
news:OJ3ma.462340$sf5.784124 at rwcrnsc52.ops.asp.att.net...
[snip]
> 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.
Is this more elegant:
>>> f = file('somefile', 'r')
>>> for line in f.readlines():
... processTheLine(line)
...
>>> f.close()
Or in newer Pythons (at least 2.2.1, maybe earlier, too - I can't remember):
>>> f = file('somefile', 'r')
>>> for line in f:
... processTheLine(line)
...
>>> f.close()
greg
More information about the Python-list
mailing list