iterating over lines in a file
Roger Upole
rupole at compaq.net
Thu Jul 20 18:51:10 EDT 2000
I must take exception to your insistence that
"Everything should be done ONCE, and only ONCE. In ONE
place in the code."
Besides sounding didactic, it is also completely false. In many cases,
an initial read is necessary to determine how (or even if) the rest of a
file will be processed. Also, different code may need to be called if
the file is empty.
Additionally, this overly simplistic programming style would be completely
inadequate for most involved programming tasks.
Roger Upole
"Alex Martelli" <alex at magenta.com> wrote in message
news:8l73an01lgb at news2.newsguy.com...
> "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