python - 读取整个文件是否会使文件句柄保持打开状态?

标签 python file-io filehandle

如果您使用 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/

相关文章:

python - 从numpy数组中随机选择一段数字

perl - 设置一个文件句柄以便悄悄地跳过对其的打印?

perl - 打开文件句柄或分配标准输出

android - 如何将文件添加到 Android 项目,然后使用 NDK 加载它

java - 读/写文件不会写入输出

css - 有没有办法使文件输入上的 native `browse` 按钮更大跨浏览器?

perl - 在程序中使用 __DATA__

python - 使用python从语料库中提取最频繁的单词

python - Pandas - 使用可变列输入计算新列

python - 计算给定两列值的天数差异