The rap against "while True:" loops
kyrie at uh.cu
Mon Oct 12 18:59:34 CEST 2009
On Monday 12 October 2009 09:47:23 am Xavier Ho wrote:
> On Mon, Oct 12, 2009 at 11:32 PM, Luis Zarrabeitia <kyrie at uh.cu> wrote:
> > Actually, in python, this works even better:
> > for lin in iter(file_object.readline, ""):
> > ... do something with lin
> What about ....
> >>> with open(path_string) as f:
> >>> for line in f:
> >>> # do something
You are right, of course!
Even my for should've been:
for lin in file_object:
and nothing more.
I use that iter "trick" only when I don't want the buffering (like, when I'm
reading from stdin in a squid authenticator helper).
I guess that the 'for line in f' is so... natural for me, that the only reason
I could think for writing "while True" for a file iteration was when I needed
to use readline explicitly.
But yes, "with"!
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
More information about the Python-list