How to do this in Python?

Ulrich Eckhardt eckhardt at satorlaser.com
Wed Mar 18 07:09:14 EDT 2009


Grant Edwards wrote:
>   with open(filename,"rb") as f:
>     while True:
>       buf = f.read(10000)
>       if not buf: break
>       # do something

The pattern 

  with foo() as bar:
      # do something with bar

is equivalent to 

  bar = foo()
  if bar:
      # do something with bar

except for the calls to __enter__ and __exit__, right? What I was wondering
was whether a similar construct was considered for a while loop or even an
if clause, because then the above could be written like this:

  if open(filename, 'rb') as f:
      while f.read(1000) as buf:
          # do something with 'buf'

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list