How to do this in Python?

Hrvoje Niksic hniksic at xemacs.org
Wed Mar 18 04:45:22 EDT 2009


Luis Zarrabeitia <kyrie at uh.cu> writes:

> One could use this: 
>
> with open(filename, "rb") as f:
>     for buf in iter(lambda: f.read(1000),''):
>         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