proposal: another file iterator

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Paul Rubin

    #1

    proposal: another file iterator

    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(blo cksize): ...

    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?
  • Raymond Hettinger

    #2
    Re: proposal: another file iterator

    Paul Rubin wrote:[color=blue]
    > 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(blo cksize): ...
    >
    > 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?[/color]

    +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(so mefile.read, blocksize), ''):
    . . .

    Raymond

    Comment

    Working...