line-by-line file read

Michael Stenner mstenner at phy.duke.edu
Fri Mar 15 07:30:10 EST 2002


OK, so the wonderful flow of the "warty range" thread inspired me to
ask the following style question:

I often find myself reading and processing a file line-by-line.  The
way I usually end up doing it goes something like this

    fo = open(filename)
    line = fo.readline()
    while line:
	# do the processing on "line" here
        line = fo.readline()
    fo.close()

In perl [this is the way to get responses on this list :)] I would do
some variation on

    open(IN, $filename);
    while ($line = <IN>) {
        # do the processing on "$line" here
    }
    close(IN);

I like the perl way better because it seems inelegant to have the
"line =" line repeated, and also because leaving off the second
"line =" is a common bug, albeit one that's usually found
immediately.

Anyway... just wondering if there's a preferred way to do this.

					-Michael

P.S.  I'm not trying to start a perl/python thing, really.  The only
reason I bring it up is I've been porting most of my old perl stuff to
python, and this is one of the very few things that seems "nicer" in
perl.  Much to my surprise, things are often _shorter_ in python, too!

-- 
  Michael Stenner                       Office Phone: 919-660-2513
  Duke University, Dept. of Physics       mstenner at phy.duke.edu
  Box 90305, Durham N.C. 27708-0305




More information about the Python-list mailing list