Iteration on file reading

Alex Martelli aleax at aleax.it
Sat Oct 4 04:52:33 EDT 2003


Andrew Dalke wrote:

> Paul McGuire:
>> def lineReader( strm ):
>>   while 1:
>>     yield strm.readline().rstrip("\n")
>>
>> for f in lineReader( stdin ):
>>   print ">>> " + f
> 
> You can simplify that with the iter builtin.
> 
> for f in iter(stdin.readline, ""):
>   print ">>> " + f
> 
> (Hmm... maybe I should test it?  Naaaaahhh.)

There is a difference in behavior: the readline method
returns a line WITH a trailing \n, which then gets
printed, giving a "double-spaced" effect.  Sure, you
can strip the \n in the loop body, but if you always
want a sequence of newline-stipped lines, that is
somewhat repetitious.  If the use of readline is
mandated (i.e., no direct looping on the file for one
reason or another), my favourite way of expression is:

def linesof(somefile):
    for line in iter(somefile.readline, ''):
        yield line.rstrip('\n')

not as concise as either of the above, but, I think,
a wee little bit clearer.


Alex







More information about the Python-list mailing list