【发布时间】:2023-03-16 02:23:01
【问题描述】:
我是 python 新手,对打开文件操作感到困惑。谁能帮我理解这个概念?谢谢
我在 source_file 类中打开一个文件:
class source_file:
def close_file(self):
self.source_file.close()
define use_file(self):
self.source_file = open(self.file_path, "r", encoding='gbk', errors='ignore')
with self.source_file as lines:
do_something()
print(self.source_file)
self.close_file()
print(self.source_file)
self.source_file.close()
print(self.source_file)
当我运行这个 source_file.use_file()
它显示:
<_io.textiowrapper name="C:\\Temp\\law_dev\\source\source_file.txt" mode="r" encoding="gbk">
<_io.textiowrapper name="C:\\Temp\\law_dev\\source\source_file.txt" mode="r" encoding="gbk">
<_io.textiowrapper name="C:\\Temp\\law_dev\\source\source_file.txt" mode="r" encoding="gbk">
当我使用“with”语句时,我感到困惑,它应该关闭文件。或者当我使用函数 close_file 时,它应该关闭文件。或者当我使用 self.source_file.close() 时,它应该关闭文件。
但从打印上看,他们似乎都没有真正关闭文件。我仍然可以看到这个文件句柄。 是否正确关闭?
【问题讨论】:
-
你在混合一堆语法。您只需要:
with open(filepath) as file