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

Raspberry Aether raspberryaether at e-s.invalid
Tue Feb 16 23:42:25 EST 2016


On 02/16/2016 11: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:-(
> 
> --Jach
> 

First-- IMO, don't depend on it. Instead, use something like:

with open('foo.txt') as f:
    for line in f:
        pass # do something here

It's one extra indent and one extra line, but it's cleaner.

To answer your question, technically, it might not-- it really
depends upon your implementation of Python. It just so happens
that the most popular version of Python (CPython, the reference
implementation) will garbage collect the file object right away.

HOWEVER. The reason the "for" will PROBABLY result in file
closure is because as soon as the for loop exits, there is no
reason to hold onto the object returned by "open", so it is
disposed. When file objects are disposed, they are closed.

IMO, don't depend on this behaviour; it's bad form.



More information about the Python-list mailing list