gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:18:46 24 4
gpt4 key购买 nike

如果我从文件 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com