How to do this in Python?

andrew cooke andrew at
Tue Mar 17 23:30:06 CET 2009

Jim Garrison wrote:
> 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 (( > 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 =
>          while len(buf) > 0
>              # do something....
>              buf =

embarrassed by the other reply i have read, but not doing much binary i/o
myself, i suggest:

with open(...) as f:
  while (True):
    buf =
    if not buf: break

but are you sure you don't want:

with open(...) as f:
  for line in f:


More information about the Python-list mailing list