2011-03-19 44 views

回答

23

这里close()发生在file对象从内存中释放时,作为其删除逻辑的一部分。因为其他虚拟机上的现代Pythons(如Java和.NET)无法控制何时从内存中释放对象,所以它不再被认为是open()的好Python,没有close()。今天的建议是使用一个with声明,其中明确请求close()时,会退出块:

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 
+0

对我来说确定很好的答案。 – philnext 2011-03-19 16:15:06

+0

是否可以内联或没有临时'f'? – 2014-10-10 16:17:44

+0

是的,我已经补充了这个问题,以显示如何不为该文件创建一个名称“f”。 – 2014-10-10 17:25:48