How to do this in Python?

Grant Edwards grante at visi.com
Wed Mar 18 04:59:30 CET 2009


On 2009-03-17, Jim Garrison <jgarrison at troux.com> 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 ((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)

with open(filename,"rb") as f:
  buf = f.read(10000)
  if not f: break
  # do something

-- 
Grant




More information about the Python-list mailing list