an ugly file-reading pattern
Skip Montanaro
skip at pobox.com
Sat Apr 12 22:34:31 EDT 2003
Istvan> if I choose to process the file line by line the "Learning
Istvan> Python" book advises me to use the following atrocity:
Istvan> while 1:
Istvan> line = file.readline()
Istvan> if not line: break
Istvan> Maybe I'm picky here but having to start an infinite loop then
Istvan> needing a conditional to break out of it is anything but an
Istvan> elegant pattern.
Istvan> This has left me wondering about python,
Recent versions of Python (2.2 and later) allow this:
file = file("somefile")
for line in file:
process(line)
It does the right thing from an efficiency standpoint, neither slurping the
file in all at once nor reading it line-by-line or char-by-char.
Note also that in 2.2 and later there is a file object in builtins ("open"
and "file" are the same object). "open" is discouraged. "file" is
preferred.
Skip
More information about the Python-list
mailing list