while c = f.read(1)

Bengt Richter bokr at oz.net
Fri Aug 19 18:39:03 EDT 2005


On Fri, 19 Aug 2005 16:31:47 +1000, John Machin <sjmachin at lexicon.net> wrote:

>Bengt Richter wrote:
>> On 18 Aug 2005 22:21:53 -0700, "Greg McIntyre" <greg at puyo.cjb.net> wrote:
>> 
>> 
>>>I have a Python snippet:
>>>
>>> f = open("blah.txt", "r")
>>> while True:
>>>     c = f.read(1)
>>>     if c == '': break # EOF
>>>     # ... work on c
>>>
>>>Is some way to make this code more compact and simple? It's a bit
>>>spaghetti.
>>>
>>>This is what I would ideally like:
>>>
>>> f = open("blah.txt", "r")
>>> while c = f.read(1):
>>>     # ... work on c
>>>
>> 
>> How about (untested):
>> 
>>    for c in iter((lambda f=open('blah.txt', 'r'): f.read(1)), ''):
>>        # ... work on c
>> 
>:-)
>Bengt, did you read on to the bit where the OP wanted to do it "more 
>nicely"? YMMV, but I think you've strayed into "pas devant les enfants" 
>territory.
>(-:
>
LOL. Mais non ;-) OTOH, I think this might cross the line:

    f = open('blah.txt')
    while [c for c in [f.read(1)] if c!='']:
        # ... work on c

;-)

Regards,
Bengt Richter



More information about the Python-list mailing list