standard input, for s in f, and buffering

Marc 'BlackJack' Rintsch bj_666 at gmx.net
Mon Mar 31 02:54:29 EDT 2008


On Sun, 30 Mar 2008 21:02:44 +0000, Jorgen Grahn wrote:

> I realize this has to do with the extra read-ahead buffering documented for
> file.next() and that I can work around it by using file.readline()
> instead.
> 
> The problem is, "for s in f" is the elegant way of reading files line
> by line. With readline(), I need a much uglier loop.  I cannot find a
> better one than this:
> 
>     while 1:
>         s = sys.stdin.readline()
>         if not s: break
>         print '####', s ,
> 
> And also, "for s in f" works on any iterator f -- so I have to choose
> between two evils: an ugly, non-idiomatic and limiting loop, or one
> which works well until it is used interactively.
> 
> Is there a way around this?  Or are the savings in execution time or
> I/O so large that everyone is willing to tolerate this bug?

You can use ``for line in lines:`` and pass ``iter(sys.stdin.readline,
'')`` as iterable for `lines`.

Ciao,
	Marc 'BlackJack' Rintsch



More information about the Python-list mailing list