Need a little parse help

Michael Hartl mhartl at post.harvard.edu
Wed May 11 00:38:28 EDT 2005


Mike mentions an important point, and I've been bitten by the
phenomenon Mike mentions---but only when *writing* to files.  They
should always be closed explicitly, as in

f = file(filename, 'w')
f.write(somestring)
f.close()

On the other hand,  I've never encountered a problem with the "for line
in file(filename)" idiom.  A similar time-saver is writing something
like

s = file(filename).read()

which puts the entire file as a string in the variable s.  In this
case, as in the file iteration case, we save two lines of code and one
variable.  It may not sound like much, but

f = file(filename)
s = f.read()
f.close()

seems much more cumbersome to me, especially when doing a lot of file
reads.

In short, my experience is that explicitly closing a file is
unnecessary when reading.  I could be wrong, though, and I'd be very
interested to see an example of either idiom above leading to problems.

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/




More information about the Python-list mailing list