proposal: another file iterator

P

Paul Rubin

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?
 
R

Raymond Hettinger

Paul said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top