如何在Python2.4中安全地打开/关闭文件

2024-03-29 01:46:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用Python编写一个小脚本,以便在我们的一个服务器上使用。服务器只安装了Python2.4.4。

直到2.5版本发布,我才开始使用Python,所以我习惯了这种形式:

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

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

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


Tags: 文件对象版本服务器txt脚本aswith
3条回答

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引发异常,则其结果是没有分配给f,并且调用f.close()是错误的。

在上述解决方案中,在此重复:

f = open('file.txt', 'r')

try:
    # do stuff with f
finally:
   f.close()

如果在成功打开文件并在尝试之前发生错误(您永远不知道…),则不会关闭该文件,因此更安全的解决方案是:

f = None
try:
    f = open('file.txt', 'r')

    # do stuff with f

finally:
    if f is not None:
       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

这里还有:https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

相关问题 更多 >