Is a with on open always necessary?

Lie Ryan lie.1296 at
Sat Jan 21 06:38:44 EST 2012

On 01/21/2012 02:44 AM, 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?

It is not necessary most of the time, and most likely is not necessary 
for short-lived programs. The file handler stays open until the file 
object is garbage collected, in CPython which uses reference counting 
the file handler is closed when the last reference to the file object is 
deleted or goes out of context; in python implementations that uses 
garbage collection method, this is indeterministic.

It is only strictly necessary for programs that opens thousands of files 
in a short while, since the operating system may limit of the number of 
active file handlers you can have.

However, it is considered best practice to close file handlers; making 
it a habit will avoid problems when you least expect it.

More information about the Python-list mailing list