Iterating over a binary file

Andrew MacIntyre andymac at bullseye.apana.org.au
Wed Jan 7 05:02:46 EST 2004


On Tue, 6 Jan 2004, Derek wrote:

> 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.

I believe the canonical form is:

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

This was also the canonical form for text files, in the case where
f.readlines() wasn't appropriate, prior to the introduction of file
iterators and xreadlines().

--
Andrew I MacIntyre                     "These thoughts are mine alone..."
E-mail: andymac at bullseye.apana.org.au  (pref) | Snail: PO Box 370
        andymac at pcug.org.au             (alt) |        Belconnen  ACT  2616
Web:    http://www.andymac.org/               |        Australia




More information about the Python-list mailing list