Will file be closed automatically in a "for ... in open..." statement?

Tim Chase python.list at tim.thechases.com
Wed Feb 17 21:32:59 EST 2016

On 2016-02-17 16:51, Steven D'Aprano wrote:
> If you want the file to be closed immediately, you must:
> - use a with statement;
> - or explicitly call f.close()

I have a lot of pre-"with" code (i.e., Py2.4) that looks like

  f = open(...)

To explicitly close() correctly, you still have to pay the
one-level-of-indent cost regardless of whether you use a "with" or

Now that we have the "with" statement, it's the same cost, with no
lost functionality, but with fewer lines of messy code.

So use the "with" unless you're sadly maintaining 2.4 code like
me. :-)


More information about the Python-list mailing list