python - "reference object of a file to be reassigned to another file"意味着什么?

标签 python file

如果我从文件 example = open(example_file) 创建一个变量,然后将该文件读入变量 example_read = example.read() 那么我需要稍后关闭文件example.close()

但是如果我直接读入变量 example_read = open(example_file).read() 那么我不需要关闭它(即它没有打开)。 (来自LPTHW)

为什么已经关闭了?我不明白以下解释 - 无论是使用中间变量 example 还是直接对 example_read 完成,所做的事情不是一样吗?

"Python automatically closes a file when the reference object of a file is reassigned to another file." - TutorialsPoint

最佳答案

通过调用 open 创建的 file 对象是匿名的,因为您不创建对它的引用。一旦对该对象的 read 调用完成并且其返回值被分配给 example_read,该对象就可以被垃圾回收,此时底层文件将被关闭。但是,您不知 Prop 体何时会发生这种情况,因此文件可能会在未指定的时间内保持打开状态。

更好的做法是避免此类匿名文件对象和/或使用 with 语句来确保文件在使用完毕后关闭。

with open(example_file) as fh:
    example_read = fh.read()

这保证了 with 语句完成后文件将立即关闭,即使使用由

创建的匿名(尽管无用)对象也是如此
with open(example_file):
    # Do something without the file object.

关于python - "reference object of a file to be reassigned to another file"意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990194/

相关文章:

python - 是否有一组简单的脚本来操作某处可用的 csv 文件?

python - 如何使用 to_sql 创建表时强制使用 utf8mb4?

java - 尝试打印无框图像

regex - Perl 正则表达式一行文件

file - 使用 Apache Camel 解压缩文件?

python - 我如何在 nltk 中使用正则表达式标记器?

c# - 将多个参数从 IronPython 传递到 .NET 方法

java - 在 Java 中是否有 try/catch 的替代方法来打开文件?

python - 哪个python模块用于读取Windows中的CPU温度和处理器风扇速度?

c# - 检查文本文件是否在记事本中打开