我可以用一个关闭的文件对象做什么?

2024-09-28 20:16:10 发布

您现在位置:Python中文网/ 问答频道 /正文

当您打开一个文件时,它存储在一个open file对象中,该对象允许您访问文件上的各种方法,例如读或写。

>>> f = open("file0")
>>> f
<open file 'file0', mode 'r' at 0x0000000002E51660>

当然,完成后,应该关闭文件以防止占用内存空间。

>>> f.close()
>>> f
<closed file 'file0', mode 'r' at 0x0000000002E51660>

这会留下一个关闭的文件,以便对象仍然存在,尽管为了可读,它不再使用空间。但这有什么实际应用吗?它不能读,也不能写。不能用它重新打开文件。

>>> f.open()

Traceback (most recent call last):
  File "<pyshell#9>", line 1, in <module>
    f.open()
AttributeError: 'file' object has no attribute 'open'

>>> open(f)

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    open(f)
TypeError: coercing to Unicode: need string or buffer, file found

除了标识文件对象正在被引用但已关闭之外,此已关闭的文件对象是否有实际用途?


Tags: 文件对象mostmodelineopencallat
1条回答
网友
1楼 · 发布于 2024-09-28 20:16:10

一种用法是使用该名称重新打开文件:

open(f.name).read()

当使用NamedTemporaryFile更改文件内容时,我使用name属性来写入更新的内容,然后用^{}替换原始文件:

with open("foo.txt") as f, NamedTemporaryFile("w", dir=".", delete=False) as temp:
    for line in f:
        if stuff:
            temp.write("stuff")

shutil.move(temp.name, "foo.txt")

如前所述,您可以使用f.closed查看文件是否真正关闭。

相关问题 更多 >