iterating over lines in a file

Alex Martelli alex at magenta.com
Thu Jul 20 10:41:38 EDT 2000


"Roger Upole" <rupole at compaq.net> wrote in message
news:hMrd5.49275$e6.2860918 at pouncer.easynews.com...
> Using an initial read is a common enough idiom in any language.

It is extremely rare in languages which allow assignment in
expressions, and would normally denote lack of familiarity
with the language's idioms.

> f=open('filename','r')
> fline = f.readline()
> while fline:
>     ....
>     fline = f.readline()

Everything should be done ONCE, and only ONCE.  In ONE
place in the code.  This expands the abstract operation
"get next thingy if any" in two places, just because of a
language quirk.

> >     def readline(self):
> >         line = self.source.readline()
> >         self.line = line
> >         return line             # may be empty, thus false

I don't see why not just:

    def readline(self):
        self.line = self.source.readline()
        return self.line

Seems to have exactly the same semantics; the local-variable
line does not appear to be playing any role.


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

The fileinput module does just that in a very elegant way, IMHO:

import fileinput

for line in fileinput.input("myfile.txt"):
    # do whatever you wish with line


Alex






More information about the Python-list mailing list