iterating over lines in a file

Roger Upole rupole at compaq.net
Wed Jul 19 20:32:13 EDT 2000


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