If you read an entire file with content = open('Path/to/file', 'r').read() is the file handle left open until the script exits? Is there a more concise method to read a whole file?
If you read an entire file with content = open(‘Path/to/file’, ‘r’).read() is the file
Share
The answer to that question depends somewhat on the particular Python implementation.
To understand what this is all about, pay particular attention to the actual
fileobject. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediately after theread()call returns.This means that the file object is garbage. The only remaining question is “When will the garbage collector collect the file object?”.
in CPython, which uses a reference counter, this kind of garbage is noticed immediately, and so it will be collected immediately. This is not generally true of other python implementations.
A better solution, to make sure that the file is closed, is this pattern:
which will always close the file immediately after the block ends; even if an exception occurs.
Edit: To put a finer point on it:
Other than
file.__exit__(), which is “automatically” called in awithcontext manager setting, the only other way thatfile.close()is automatically called (that is, other than explicitly calling it yourself,) is viafile.__del__(). This leads us to the question of when does__del__()get called?— https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203
In particular:
— https://docs.python.org/3.5/reference/datamodel.html#objects-values-and-types
(Emphasis mine)
but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!