Will file be closed automatically in a "for ... in open..." statement?
steve+comp.lang.python at pearwood.info
Wed Feb 17 00:51:31 EST 2016
On Wednesday 17 February 2016 15:04, 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:-(
This has nothing to do with "for". You would get exactly the same behaviour
f = open("some file", "r")
x = f.read(20)
x = f.read(30)
x = f.read()
So long as the variable "f" is in-scope, the file will stay open. If the
above code is in a function, "f" goes out of scope when the function
returns. If the above code is at the top level of the module, "f" will stay
in scope forever, or until you either delete the variable from the scope:
or re-assign to something else:
f = "hello world"
At this point, after the function has exited, and the variable has
completely gone out of scope, what happens?
The garbage collector will:
- reclaim the memory used by the object;
- close the file.
BUT there is no promise WHEN the file will be closed. It might be
immediately, or it might be when the application shuts down.
If you want the file to be closed immediately, you must:
- use a with statement;
- or explicitly call f.close()
otherwise you are at the mercy of the interpreter, which will close the file
whenever it wants.
More information about the Python-list