iterating over lines in a file

Alex Martelli alex at magenta.com
Sat Aug 5 12:11:58 EDT 2000


"gbp" <gpepice1 at nycap.rr.com> wrote in message
news:398C2FC4.11E4214E at nycap.rr.com...
>
> That person is coming from a Perl background and in Perl all those
> issues are taken care of automatically.  Perl would not crash if given
> an empty file.

I'm not quite sure what this comment is about -- presumably it's
responding to Roger Upole's observation:

> > 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.

And "that person" is supposed to be me, to which Roger was replying -- I
was suggesting the use of:

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


Now, it's quite true that I also have Perl in my background (as well as
C++, Java, Fortran, C, Pascal, Rexx, IBM/370 BAL, x86 assembler, Icon,
awk, Scheme, Tcl, Sather, Visual Basic, GPL, APL, APL2, and several
other languages, in different amounts...), but exactly because of this
I'm perplexed by your suggestion that (in any language) "all those issues
are taken care of automatically".  If an empty file needs to be handled
differently from a non-empty one, or if the first few lines determine
what is to be done with the rest (e.g., the first few lines are to be
taken as 'headers', as for news, e-mails, responses from an HTTP server,
etc), as Roger suggested, then it's going to have to be your program
that 'takes care' of it.

It's not a matter of "crashing".  The above-mentioned Python idiom
will not 'crash' if myfile.txt is empty, just as the Perl equivalent
won't; but each will simply call zero times the "do whatever" part.
If this "natural extrapolation" is not what is desired, then _some_
special-purpose test, and if/else construct (or equivalent thereof),
will have to be coded by the programmer, whatever language is in use!


Alex






More information about the Python-list mailing list