iterating over lines in a file

Donn Cave donn at u.washington.edu
Fri Jul 21 12:36:18 EDT 2000


Quoth "Roger Upole" <rupole at compaq.net>:
| 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.

Whatever.  You do what you want.  But when that means stuff like this,

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

eventually you're going to have a debugging problem when you change that
function at one site and neglect to make the same change at the other.
That was the context for that statement.

If you have to sort this out here before you can go on to do anything
today, clarity may come if you look at it this way:  what is a "thing",
when we say "everything should be done once?"  Does that mean f.readline(),
i.e., f.readline() can be called in only one place?  If we have two
places in our program that test __name__ == '__main__', should those 
two be consolidated into one?  What about "import sys"?

As stupid as that would be, to write code like the example above just
to avoid a "while 1" is worse, because at least our "one" philosophy
has an explanation.

If you're looking for a sensible statement that you wouldn't have to
take exception to, what if a "thing" is a section of code that if
duplicated would certainly be subject to the same change issues in
each instance.  I.e., if changed at site 1 it would certainly have
to be changed in the same way at site 2.  Where that's not the case,
we are evidently talking about a different "thing", something that
looks the same but has a different meaning.  No one would want to
argue that two things with different meanings should be forced
together, only when the meaning is the same.

	Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list