iterating over lines in a file

David Bolen db3l at fitlinxx.com
Wed Jul 19 21:38:28 EDT 2000


nobody <no at bo.dy> writes:

> could somebody enlighten me, please? and is there any easier way to
> iterate over lines in a file without resorting to ugly break statements?

Not without duplicating your actual I/O operation (the only real way
to avoid a break is to compare the current I/O within the expression
of the loop, so you have to load a value to check both prior to the
loop and then within the loop for the next cycle).

The basic Python approach to iteratiing over a file would be:

    while 1:
        line = file.readline()
        if not line: break

        (... operations to perform ...)

Yes, it has a break in it (although I personally don't consider
'break' ugly - break and continue are often the most elegant way to
handle flow), and yes, it seems clumsy to those of us used to
assignments within expressions, but its the sort of thing you just
acknowledge and move on - it's really not that big a deal.

The class you found wraps things up a bit, and effectively hides the
assignment within the class, so you can use the direct expression
approach in your higher level code, but that's about it.

There's also a FAQ on this common question, available at:

    http://www.python.org/doc/FAQ.html#6.30


--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list