gpt4 book ai didi

python - 关闭作为对象 {str} 打开的文件

转载 作者:行者123 更新时间:2023-12-01 02:14:27 25 4
gpt4 key购买 nike

我正在使用 .read() 方法打开文件 bug_html_file。 Python 将其用作内存中的 {str} 对象,对吧?

bug_html_file = open(bgz_sfx_html_file, 'r', encoding='utf-8').read()

是否需要以任何方式关闭该句柄?是否创建了任何文件句柄?

最佳答案

您应该始终关闭打开的文件。例如,如果您在解释器中运行该文件,然后在解释器仍然打开的情况下尝试删除该文件,您将无法删除该文件,因为该文件被标记为“正在使用”。打开该文件的方式会丢失文件对象的引用(由 open 返回),因此之后无法关闭它。

正如 @Chris_Rands 建议的那样,使用 with block 来确保退出该 block 后文件立即关闭:

with open('bug_html_file.txt', 'r') as fp:
data = fp.read()
# here the file is closed (if you try `read`ing from `fp` you'll raise an error)

关于python - 关闭作为对象 {str} 打开的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48459852/

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