在内联“打开和写入文件”中,close()是隐式的吗?
在Python(> 2.7)中执行代码:
open('tick.001', 'w').write('test')
结果与:
ftest = open('tick.001', 'w')
ftest.write('test')
ftest.close()
在哪里可以找到有关此内联功能“关闭”的文档?
-
在
close()
当发生此file
对象从存储器释放,因为它的缺失逻辑的一部分。由于其他虚拟机(例如Java和.NET)上的现代Python无法控制何时从内存中释放对象,因此不再open()
喜欢不使用python这样的对象close()
。今天的建议是使用一条with
语句,该语句close()
在退出该块时显式请求a
:with open('myfile') as f: # use the file # when you get back out to this level of code, the file is closed
如果不需要
f
文件名,则可以as
从语句中省略该子句:with open('myfile'): # use the file # when you get back out to this level of code, the file is closed