Is a with on open always necessary?

Steven D'Aprano steve+comp.lang.python at
Fri Jan 20 19:48:08 EST 2012

On Fri, 20 Jan 2012 15:44:17 +0000, Andrea Crotti wrote:

> I normally didn't bother too much when reading from files, and for
> example I always did a
> content = open(filename).readlines()
> But now I have the doubt that it's not a good idea, does the file
> handler stays open until the interpreter quits?

The file will stay open until:

1) you explicitly close it;
2) the reference to the open file goes out of scope and is garbage 
collected; or
3) the Python environment shuts down

whichever happens first.

In the case of #2, the timing is a matter of implementation detail. 
CPython and PyPy currently close the file immediately the last reference 
to it goes out of scope (but that's not a promise of the language, so it 
could change in the future); Jython and IronPython will eventually close 
the file, but it may take a long time.

Except for the quickest and dirtiest scripts, I recommend always using 
either the "with file as" idiom, or explicitly closing the file.


More information about the Python-list mailing list