Iterating over a binary file

Peter Abel PeterAbel at gmx.net
Wed Jan 7 08:20:50 EST 2004


"Derek" <none at none.com> wrote in message news:<btf5j8$6g26f$1 at ID-46268.news.uni-berlin.de>...
> 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.

There's an aproach to mimic the following C-statements in Python:

while (result = f.read(1024))
  {
    do_some_thing(result);
  }

>>> def assign(val):
... 	global result
... 	result=val
... 	return val
... 

>>> f=file('README.txt','rb')

>>> while assign(f.read(1024)):
... 	print len(result)
... 

121

>>> f.close()

Regards
Peter



More information about the Python-list mailing list