When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.
因此,将close()优雅地与try/finally一起使用:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:
>>> with open('workfile', 'r') as f:
... read_data = f.read()
>>> f.closed
True
见docs.python.org:
因此,将
close()
优雅地与try/finally
一起使用:这确保了即使
# do stuff with f
引发异常,f
仍将正确关闭。注意
open
应该出现在try
的外部。如果open
本身引发异常,则文件未打开,无需关闭。此外,如果open
引发异常,则其结果是没有分配给f
,并且调用f.close()
是错误的。在上述解决方案中,在此重复:
如果在成功打开文件并在尝试之前发生错误(您永远不知道…),则不会关闭该文件,因此更安全的解决方案是:
如果您使用以下选项,则无需根据文档关闭文件:
这里还有:https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
相关问题 更多 >
编程相关推荐