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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
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
file
object. In your code, that object is mentioned only once, in an expression, and becomes inaccessible immediatly after theread()
call returns.This means that the file object is garbage. The only remaining question is "When will the garbage collecter 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 awith
context 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?-- http://blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx
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!
You can use pathlib.
For Python 3.5 and above:
For lower versions of Python use pathlib2:
Then:
This is the actual
read_text
implementation: