如何在python中安全打开/关闭文件2.4 [英] How to safely open/close files in python 2.4
问题描述
我正在使用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.
我没有开始使用Python,直到2.5出来,所以我习惯了以下形式:
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之前没有语句的 m无法找到手动清理文件对象的正确方法的示例。
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时,安全处理文件对象的最佳做法是什么? / p>
What's the best practice for disposing of file objects safely when using old versions of python?
推荐答案
使用 try / finally
:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
这样可以确保即使#do f with f
引发异常, f
仍将被正确关闭。
This ensures that even if # do stuff with f
raises an exception, f
will still be closed properly.
请注意,打开
应该出现在之外 尝试
。如果打开
本身引发异常,则该文件未打开,不需要关闭。另外,如果打开
引发异常,它的结果是不分配给 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!