How to do this in Python?

Hrvoje Niksic hniksic at
Wed Mar 18 09:45:22 CET 2009

Luis Zarrabeitia <kyrie at> writes:

> One could use this: 
> with open(filename, "rb") as f:
>     for buf in iter(lambda:,''):
>         do_something(buff)

This is by far the most pythonic solution, it uses the standard 'for'
loop, and clearly marks the sentinel value.  lambda may look strange
at first, but this kind of thing is exactly what lambdas are for.
Judging by the other responses, it would seem that few people are
aware of the two-argument 'iter'.

> but I don't really like a lambda in there. I guess one could use
> functools.partial instead, but it still looks ugly to me. Oh, well,
> I guess I also want to see the canonical way of doing it.

I believe you've just written it.

More information about the Python-list mailing list