How to do this in Python?

Jim Garrison jgarrison at troux.com
Tue Mar 17 23:04:36 CET 2009


I'm an experienced C/Java/Perl developer learning Python.

What's the canonical Python way of implementing this pseudocode?

     String buf
     File   f
     while ((buf=f.read(10000)).length() > 0)
     {
         do something....
     }

In other words, I want to read a potentially large file in 10000 byte
chunks (or some other suitably large chunk size).  Since the Python 
'file' object implements __next__() only in terms of lines (even,
it seems, for files opened in binary mode) I can't see how to use
the Python for statement in this context.

Am I missing something basic, or is this the canonical way:

     with open(filename,"rb") as f:
         buf = f.read(10000)
         while len(buf) > 0
             # do something....
             buf = f.read(10000)



More information about the Python-list mailing list