Need a little parse help

James Stroud jstroud at mbi.ucla.edu
Wed May 11 13:55:03 EDT 2005


My understanding is that Python code should keep as many possible 
implementations in mind. For example, I have been told that it would be 
unwise to do something like this in Jython because the Java GC will not 
reclaim the file resources:

for afile in more_than_just_a_few_files:
  for aline in open(afile):
    doit(aline)
  # unwisely forget to close afile

I could be wrong, though.

James

On Tuesday 10 May 2005 09:38 pm, Michael Hartl wrote:
> 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/

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list