How to do this in Python? - A "gotcha"
Andrii V. Mishkovskyi
mishok13 at gmail.com
Wed Mar 18 12:01:22 EDT 2009
On Wed, Mar 18, 2009 at 5:51 PM, Jim Garrison <jhg at acm.org> wrote:
> Jim Garrison wrote:
>>
>> Luis Zarrabeitia wrote:
>>>
>>> On Tuesday 17 March 2009 06:04:36 pm Jim Garrison wrote:
>>> with open(filename, "rb") as f:
>>> for buf in iter(lambda: f.read(1000),''):
>>> do_something(buf)
>>
>> This is the most pythonic solution yet.
>>
>> Thanks to all the responders who took time to ponder this seemingly
>> trivial question. I learned a lot about the Python mind-set.
>
> I just tried the code as given above and it results in an infinite loop.
>
> Since f.read() returns a byte string when in binary mode, the sentinel
> has to be b''. Is there a value that will compare equal to both '' and b''?
>
> It's a shame the iter(o,sentinel) builtin does the
> comparison itself, instead of being defined as iter(callable,callable)
> where the second argument implements the termination test and returns a
> boolean. This would seem to add much more generality... is
> it worthy of a PEP?
Just before you start writing a PEP, take a look at `takewhile'
function in `itertools' module. ;)
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
Wbr, Andrii V. Mishkovskyi.
He's got a heart of a little child, and he keeps it in a jar on his desk.
More information about the Python-list
mailing list