Iterating over a binary file

Anton Vredegoor anton at vredegoor.doge.nl
Wed Jan 7 00:44:29 EST 2004


Paul Rubin <http://phr.cx@NOSPAM.invalid> wrote:

>    Statement                              Reading difficulty
>    =========                              ==================
>
>       f = file(filename, 'rb')                    1
>       while len(data := f.read(1024)) > 0:        2
>         someobj.update(data)                      1
>       f.close()                                   1
>
>
>    Total reading difficulty:                      5

In Python it can be done even simpler than in C, by making the
"someobj.update" method return the length of the data:

#derek.py

class X:
    
    def update(self,data): 
        #print a chunk and a space
        print data,
        return len(data)

def test():
    x = X()
    f = file('derek.py','rb')
    while x.update(f.read(1)):
        pass
    f.close()

if __name__=='__main__':
    test()

IMHO the generator solution proposed earlier is more natural to some
(all?) Python programmers.

Anton



More information about the Python-list mailing list