[Tutor] Unusual behavior in readline

wesley chun wescpy at gmail.com
Tue Aug 8 23:59:33 CEST 2006


summarizing what folks have already said plus a few more tweaks such
as moving the close() to finally (2.5+), following the style guideline
of variable non-titlecasing, removing unused variables, etc.:

#!/usr/bin/env python2.5

def processFile(inputfile):
    try:
        fh = open(inputfile, "r")
        for entry in fh:
            print "Entry = %s" % entry.strip()
    except IOError, e:
        print "\nError occurred opening %s for input\n" % inputfile
    finally:
        fh.close()

if __name__ == '__main__':
    processFile('phone')

we get this output:

$ tony.py
Entry = Alias,Phone
Entry = JANE SMITH,12131234567

the try-except-finally statement was unified (again) coming up in 2.5.
 i say again because it was actually there before but removed in
version 0.9.6.  :-)

how about some 2.6 fun and using the with statement to get rid of
finally and closing the file, as a 2.5 preview?

#!/usr/bin/env python2.5

from __future__ import with_statement

def processFile(inputfile):
    try:
        with open(inputfile, "r") as fh:
            for entry in fh:
                print "Entry = %s" % entry.strip()
    except IOError, e:
        print "\nError occurred opening %s for input\n" % inputfile

the context management of the with statement will automagically close
the file regardless of exceptions so you do not need to worry about
it.  in 2.6, both 'with' and 'as' become keywords -- you will be
warned in 2.5.

cheers,
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list