while c = f.read(1)

Reinhold Birkenfeld reinhold-birkenfeld-nospam at wolke7.net
Sun Aug 21 11:43:07 CEST 2005


John Machin wrote:

> ... AND it's about time that list is updated to include False explicitly 
>   -- save nitpicking arguments about whether False is covered by 
> "numeric zero of all types" :-)

Done.

>> If I try:
>> 
>>   f = open("blah.txt", "r")
>>   while (c = f.read(1)) != '':
>>       # ... work on c
>> 
>> I get a syntax error also. :(
>> 
>> Is this related to Python's expression vs. statement syntactic
>> separation? How can I be write this code more nicely?
>> 
>> Thanks
>> 
> 
> How about
>     for c in f.read():
> ?
> Note that this reads the whole file into memory (changing \r\n to \n on 
> Windows) ... performance-wise for large files you've spent some memory 
> but clawed back the rather large CPU time spent doing f.read(1) once per 
> character. The "more nicely" factor improves outasight, IMHO.
> 
> Mild curiosity: what are you doing processing one character at a time 
> that can't be done with a built-in function, a standard module, or a 
> 3rd-party module?

Don't forget

for line in f:
    for c in line:
        # do stuff

Reinhold



More information about the Python-list mailing list