如果您使用 content = open('Path/to/file', 'r').read()
读取整个文件,文件句柄是否保持打开状态直到脚本退出?有没有更简洁的方法来读取整个文件?
最佳答案
这个问题的答案在某种程度上取决于特定的 Python 实现。
要了解这一切,请特别注意实际的 file
对象。在您的代码中,该对象仅在表达式中被提及一次,并且在 read()
调用返回后立即变得不可访问。
这意味着文件对象是垃圾。剩下的唯一问题是“垃圾收集器何时会收集文件对象?”。
在使用引用计数器的 CPython 中,这种垃圾会立即被注意到,因此会立即被收集。其他 python 实现通常不是这样。
更好的解决方案是确保文件已关闭,是这种模式:
with open('Path/to/file', 'r') as content_file:
content = content_file.read()
在 block 结束后总是会立即关闭文件;即使发生异常。
编辑:更详细地说:
除了 file.__exit__()
,它在 with
上下文管理器设置中“自动”调用,这是 file.close( )
是通过 file.__del__()
自动调用的(也就是说,除了自己显式调用之外)。这就引出了一个问题,__del__()
什么时候被调用?
A correctly-written program cannot assume that finalizers will ever run at any point prior to program termination.
-- https://devblogs.microsoft.com/oldnewthing/20100809-00/?p=13203
特别是:
Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable.
[...]
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 has 6 different garbage collection implementations !
关于python - 读取整个文件是否会使文件句柄保持打开状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7409780/