[Tutor] do I need f.close()

Danny Yoo dyoo at cs.wpi.edu
Tue Jun 10 20:31:57 CEST 2008


>>  f = open(conf, 'w')
>>  f.writelines(lines)
>>  f.close()
>>
>>  Is it as safe to use the following ....
>>
>>  open(conf, 'w').writelines(lines)
>>
>>  ie no close() to flush the data, but also not assigned an object name
>>  so am I right in thinking that as the object is 'reclaimed' close() is
>>  automatically called ?
>
> True. And not, imho, "bad programming"


I have to disagree.  The effect of the above line is sensitive to the 
behavior of the underlying implmentation.  As Kent mentioned, CPython says 
that it'll call close() immediately when the count of the last reference 
to the file object goes to zero.  But Jython and IronPython on the other 
hand make no such guarantees.

This is one of those places where the behavior of the above code is, 
unfortunately, undefined in the language specification.  We have to dig 
ourselves out of such swamps: we should avoid getting into trouble by 
explicit close() of the resource.

Python 2.5's 'with' form addresses this problem.  The documentation on 
file.close() has an example:

     http://www.python.org/doc/lib/bltin-file-objects.html#l2h-297


So the code above could become:

##############################################
with open(conf, 'w') as f: f.writelines(lines)
##############################################

You'll need to add the 'from __future__ import with_statement' at the top, 
since this is a Python 2.5 specific feature.  The code is almost as short 
as the previous and it guarantees that f will be flushed and closed after 
the statement's done.


More information about the Tutor mailing list