Is a with on open always necessary?

Arnaud Delobelle arnodel at
Fri Jan 20 10:56:26 EST 2012

On 20 January 2012 15:44, Andrea Crotti <andrea.crotti.0 at> 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?

IIRC it stays open until garbage collected (it's closed in the file
object's __del__ method).  When the file object is collected is an
implementation detail, although in CPython it will happen straight
away because it uses reference counting.

> So maybe doing a
> with open(filename) as f:
>     contents = f.readlines()

That's what I do, unless I'm in an interactive session.


More information about the Python-list mailing list