stdio EOF ?

Duncan Booth duncan at
Tue Aug 13 13:12:18 CEST 2002

Jacek Generowicz <jacek.generowicz at> wrote in 
news:tyfd6sn85mt.fsf at

>> The standard idiom for this is:
>>      while 1:
>>         line = file.readline()
>>         if not line:
>>            break
>>         ...
>> The .readline method of a file object returns a complete line (including
>> the trailing newline), or an empty string in the case of EOF.
> ... unfortunately empty lines are meaningful in the relevant context
> (separation of datasets); an empty line has a meaning different from
> that of EOF (no more datasets after this one).

I think you misunderstood the bit about empty lines. The when the file 
contains a line that is otherwise blank, the value returned is a string 
containing the newline character. You only get an empty value returned at 
the end of the file.

It does indeed appear that the buffering breaks the 'for var in fileobject' 
idiom when the fileobject is an interactive stream. You should use the 
while loop as above.

If you don't like having to strip all the newlines from each line, then an 
alternative is to write a generator to do it for you:

from __future__ import generators
import sys

def filelines(f):
    while 1:
        line = f.readline()
        if not line: break
        yield line[:-1]

for line in filelines(sys.stdin):
    print "**",`line`,"**"

Duncan Booth                                             duncan at
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list