proposal: another file iterator
Raymond Hettinger
python at rcn.com
Sun Jan 15 21:24:59 EST 2006
Paul Rubin wrote:
> I find pretty often that I want to loop through characters in a file:
>
> while True:
> c = f.read(1)
> if not c: break
> ...
>
> or sometimes of some other blocksize instead of 1. It would sure
> be easier to say something like:
>
> for c in f.iterbytes(): ...
>
> or
>
> for c in f.iterbytes(blocksize): ...
>
> this isn't anything terribly advanced but just seems like a matter of
> having the built-in types keep up with language features. The current
> built-in iterator (for line in file: ...) is useful for text files but
> can potentially read strings of unbounded size, so it's inadvisable for
> arbitrary files.
>
> Does anyone else like this idea?
+1 It would be nice to see this replace the old API where you had to
test for an empty return value.
FWIW, I've seen it expressed using other tools:
for c in iter(partial(somefile.read, blocksize), ''):
. . .
Raymond
More information about the Python-list
mailing list