Newbie question about file input

Peter Hansen peter at
Mon Aug 16 18:33:54 CEST 2004

Elcio Ferreira wrote:
>>while 1:
>>  line = zf.readline()
>>  if not line:
>>    break
> Newbie's question:
> Isn't it a strange way to do a loop? Create a loop with a foo
> condition and use an if to break it?

It's a little unusual compared to many other languages, but
Python often tries to have only one obvious way to do something.
Other languages have two or three or even more different ways
to do 'while' style loops, while Python has only one.  The
downside, if you want to think of it as such, is that idioms
like the above can seem a little "off".

On the other hand, perhaps once you've coded Python for a while
you will start to feel that the above is quite straightforward
and flows from your fingers pretty easily, because you don't
have to stop and think of _which_ of the available loops
you should use.

> =====
> line=zf.readline()
> while line:
>     . . .
>     line=zf.readline()
> =====
> Isn't this code much more easy to understand?

Perhaps... but less maintainable.  Duplication is almost
always a bad thing in programming, and the above is prone
to various kinds of errors, especially if you or someone else
goes back to change the code in the future.

It is possible with Python to restructure things like the
above to be both readable and maintainable, either by using
classes or, more recently, with generators:

def readlines(f):
     while 1:
         line = f.readline()
         if not line:
         yield line

then in the rest of your code you can just do this:

for line in readlines(zf):
     # do something with line...

Of course, the "file" object now allows this natively, so
you don't even have to write the above, but the point is
that if you don't like the "while 1:/test/break" idiom,
there are alternatives.


More information about the Python-list mailing list