Iterating over a binary file

Paul Rubin http
Tue Jan 6 15:58:38 EST 2004


"Derek" <none at none.com> writes:
> f = file(filename, 'rb')
> data = f.read(1024)
> while len(data) > 0:
>     someobj.update(data)
>     data = f.read(1024)
> f.close()
> 
> The above code works, but I don't like making two read() calls.  Any
> way to avoid it, or a more elegant syntax?  Thanks.

You can make it even uglier:

    f = file(filename, 'rb')
    while 1:
      data = f.read(1024)
      if len(data) <= 0:
        break
      someobj.update(data)
    f.close()

There's been proposals around to add an assignment-expression operator
like in C, so you could say something like

    f = file(filename, 'rb')
    while len(data := f.read(1024)) > 0:
      someobj.update(data)
    f.close()

but that's the subject of holy war around here too many times ;-).  Don't
hold your breath waiting for it.



More information about the Python-list mailing list