当您打开一个文件时,它存储在一个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
除了标识文件对象正在被引用但已关闭之外,此已关闭的文件对象是否有实际用途?
一种用法是使用该名称重新打开文件:
当使用NamedTemporaryFile更改文件内容时,我使用name属性来写入更新的内容,然后用^{} 替换原始文件:
如前所述,您可以使用
f.closed
查看文件是否真正关闭。相关问题 更多 >
编程相关推荐