问题描述
如果使用content = open('Path/to/file', 'r').read()
读取了整个文件,则文件句柄是否保持打开状态,直到脚本退出?有没有更简洁的方法来读取整个文件?
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?
推荐答案
该问题的答案在某种程度上取决于特定的Python实现.
The answer to that question depends somewhat on the particular Python implementation.
要了解所有内容,请特别注意实际的file
对象.在您的代码中,该对象在表达式中仅被提及一次,并且在read()
调用返回后立即变得不可访问.
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 immediately after the read()
call returns.
这意味着文件对象是垃圾.剩下的唯一问题是垃圾收集器何时收集文件对象?".
This means that the file object is garbage. The only remaining question is "When will the garbage collector collect the file object?".
会立即注意到这种垃圾,因此将立即对其进行收集.对于其他python实现,通常情况并非如此.
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:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
它将始终在块结束后立即关闭文件;即使发生异常.
which will always close the file immediately after the block ends; even if an exception occurs.
要点更清楚:
除了file.__exit__()
(它是在with
上下文管理器设置中自动"调用的)之外,自动调用file.close()
的唯一其他方式(即,除了自己明确调用之外)是通过file.__del__()
.这就引出了一个问题,__del__()
什么时候被调用?
Other than file.__exit__()
, which is "automatically" called in a with
context manager setting, the only other way that file.close()
is automatically called (that is, other than explicitly calling it yourself,) is via file.__del__()
. This leads us to the question of when does __del__()
get called?
- https://devblogs.microsoft.com/oldnewthing/20100809 -00/?p = 13203
尤其是:
[...]
CPython当前使用引用计数方案,该方案具有(可选)延迟检测循环链接的垃圾的功能,该功能可在对象无法访问时立即收集大多数对象,但不能保证收集包含循环引用的垃圾.
CPython currently uses a reference-counting scheme with (optional) delayed detection of cyclically linked garbage, which collects most objects as soon as they become unreachable, but is not guaranteed to collect garbage containing circular references.
- https://docs.python. org/3.5/reference/datamodel.html#objects-values-and-types
(强调我的)
但正如它暗示的那样,其他实现可能具有其他行为.例如,PyPy 具有 6 不同的垃圾收集实施!
but as it suggests, other implementations may have other behavior. As an example, PyPy has 6 different garbage collection implementations!
这篇关于读取整个文件是否会使文件句柄保持打开状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!