gpt4 book ai didi

python - 如何在 python 2.4 中安全地打开/关闭文件

转载 作者:IT老高 更新时间:2023-10-28 21:12:36 26 4
gpt4 key购买 nike

我目前正在使用 Python 编写一个小脚本,用于我们的一台服务器上。服务器只安装了 Python 2.4.4。

直到 2.5 出来我才开始使用 Python,所以我习惯了这种形式:

with open('file.txt', 'r') as f:
# do stuff with f

但是,在 2.5 之前没有 with 语句,我无法找到有关手动清理文件对象的正确方法的示例。

在使用旧版本的 python 时,安全处理文件对象的最佳做法是什么?

最佳答案

docs.python.org :

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()

这确保即使 # do stuff with f 引发异常,f 仍将正确关闭。

请注意,open 应该出现在 try之外。如果 open 本身引发异常,则该文件未打开且无需关闭。此外,如果 open 引发异常,则其结果 not 分配给 f 并且调用 f.close() 是错误的.

关于python - 如何在 python 2.4 中安全地打开/关闭文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3770348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com