iterating over lines in a file

Olivier Dagenais olivierS.dagenaisP at canadaA.comM
Wed Jul 19 20:51:20 EDT 2000


You can get rid of the initial read if you have a function that returns
true/false and one of the parameters is passed by reference to be the actual
item.  I'm not sure Python does by-reference arguments, though...

For example (I'm not sure this works, think of it as a pseudo-example...):

def enumerate ( retval ):
    if outOfElements():
        return 0
    else:
        retval = nextElement()
        return 1

Then you call it like so:

while enumerate ( currentValue ):
    print currentValue


--
----------------------------------------------------------------------
Olivier A. Dagenais - Carleton University - Computer Science III


"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.
>
> f=open('filename','r')
> fline = f.readline()
> while fline:
>     ....
>     fline = f.readline()
>
>               Roger Upole
>
> "nobody" <no at bo.dy> wrote in message
> news:Uvqd5.21615$DZ4.69024 at news.corecomm.net...
> > assume i want to iterate a block of code over every line in a text file,
> > and that i don't want to snarf the whole thing into memory for fear
> > of coredumps or whatever. in perl (and many others) there is a simple,
> > common idiom:
> >
> > while (line = <FILE>) { block; }
> >
> > this doesn't seem to have a simple, direct analog in python. searching
> > around on the web i found a solution at faqts.com (though this newbie
> > might like to see it explained, but whatever works):
> >
> > class Reader:
> >     def __init__(self, source):
> >         self.source = source
> >     def readline(self):
> >         line = self.source.readline()
> >         self.line = line
> >         return line             # may be empty, thus false
> >
> > file = Reader(open("filename")) # i might have got this worng...?
> >
> > while (file.readline()):
> >     line = file.line
> >
> > now, this seems to me like an awful lot of typing just to get around
> > the fact that assignments in python do not seem to be expressions
> > returning the value assigned. since that is thus in several other
> > languages, and since it gives rise to several common idioms of this
> > type, i can only assume that there must be some good reason for
> > breaking this pattern in python; i just can't see what it could
> > possibly be.
> >
> > could somebody enlighten me, please? and is there any easier way to
> > iterate over lines in a file without resorting to ugly break statements?
> >
>
>





More information about the Python-list mailing list