问题描述
我目前正在使用 Python 编写一个小脚本,以便在我们的一台服务器上使用.服务器只安装了 Python 2.4.4.
I'm currently writing a small script for use on one of our servers using Python. The server only has Python 2.4.4 installed.
直到 2.5 出来我才开始使用 Python,所以我习惯了这种形式:
I didn't start using Python until 2.5 was out, so I'm used to the form:
with open('file.txt', 'r') as f:
# do stuff with f
但是,在 2.5 之前没有 with
语句,我无法找到有关手动清理文件对象的正确方法的示例.
However, there is no with
statement before 2.5, and I'm having trouble finding examples about the proper way to clean up a file object manually.
在使用旧版本的 python 时安全处理文件对象的最佳做法是什么?
What's the best practice for disposing of file objects safely when using old versions of python?
推荐答案
参见 docs.python.org:
当你处理完一个文件时,调用 f.close() 来关闭它并释放被打开的文件占用的所有系统资源.调用 f.close() 后,尝试使用文件对象将自动失败.
因此将 close()
优雅地与 try/finally
一起使用:
Hence use close()
elegantly with try/finally
:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
这确保即使 # do stuff with f
引发异常,f
仍会正确关闭.
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
注意open
应该出现在try
的外面.如果 open
本身引发异常,则文件未打开且不需要关闭.此外,如果 open
引发异常,其结果 not 分配给 f
并且调用 f.close() 是错误的
.
Note that open
should appear outside of the try
. If open
itself raises an exception, the file wasn't opened and does not need to be closed. Also, if open
raises an exception its result is not assigned to f
and it is an error to call f.close()
.
这篇关于如何在 python 2.4 中安全地打开/关闭文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!