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

Chris Angelico rosuav at gmail.com
Tue Feb 16 23:36:53 EST 2016


On Wed, Feb 17, 2016 at 3:04 PM,  <jfong at ms4.hinet.net> wrote:
> Thanks for these detailed explanation. Both statements will close file automatically sooner or later and, when considering the exceptions, "with" is better. Hope my understanding is right.
>
> But, just curious, how do you know the "for" will do it? I can't find any document about it from every sources I know. Very depressed:-(
>

It's not the 'for' loop that does it. The for loop is kinda like this:

_temp = open("foo.txt")
_temp.read() # do stuff, do stuff
_temp = None

When you stop holding onto an object, Python can get rid of it. When
that happens is not promised, though - and if you have a reference
loop, it might hang around for a long time. But when a file object is
disposed of, the underlying file will get closed.

ChrisA


More information about the Python-list mailing list