在
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 pre, the file is closed如果不需要
f文件名,则可以
as从语句中省略该子句:
with open('myfile'): # use the file# when you get back out to this level of pre, the file is closed


