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

标签 python file-io python-2.4

我目前正在使用 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/

相关文章:

python - Python 2.4 中的 SHA256 哈希

python - 如何使用 Selenium Python 单击 <a class href > 链接问题

python - 输出斐波那契数列中的素数

python - if 语句顺序错误,不确定出了什么问题

java - 使用 ObjectInputStream、ObjectOutputStream 时程序无法正确加载数据

python - 2.4 和 2.7 之间内置 round() 函数的 Python 变化

python正则表达式从字符串中删除最后一个数字

c# - 调用 await GetFileAsync() 永远不会返回并且应用程序在 WinRT 应用程序中挂起

python - 使用 Python,如何关闭网络上另一个用户正在使用的文件?

python - urllib2:如何安装代理和 http 基本身份验证处理程序作为开启器?