Iterating over a binary file
Jp Calderone
exarkun at intarweb.us
Tue Jan 6 22:24:16 EST 2004
On Tue, Jan 06, 2004 at 03:25:11PM -0500, Derek wrote:
> Pardon the newbie question, but how can I iterate over blocks of data
> from a binary file (i.e., I can't just iterate over lines, because
> there may be no end-of-line delimiters at all). Essentially I want to
> to this:
>
> 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.
>
f = file(filename, 'rb')
for data in iter(lambda: f.read(1024), ''):
someobj.update(data)
f.close()
Jp
More information about the Python-list
mailing list