明确关闭文件很重要吗? [英] Is explicitly closing files important?

查看:128
本文介绍了明确关闭文件很重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,如果您打开一个文件而不调用 close(),或关闭文件但不使用 try - 最后 with 语句,这是个问题吗?还是仅仅依靠Python垃圾收集来关闭所有文件就足以成为一种编码习惯?例如,如果有人这样做:

In Python, if you either open a file without calling close(), or close the file but not using try-finally or the "with" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:

for line in open("filename"):
    # ... do stuff ...

...这是一个问题,因为文件永远不能关闭,可能会发生阻止它被关闭的异常?或者它肯定会在结束时关闭语句,因为文件超出了范围?

... is this a problem because the file can never be closed and an exception could occur that prevents it from being closed? Or will it definitely be closed at the conclusion of the for statement because the file goes out of scope?

推荐答案

在您的示例中,文件不保证在解释器退出前关闭。在CPython的当前版本中,文件将在for循环结束时关闭,因为CPython使用引用计数作为其主要垃圾回收机制,但这是实现细节,而不是该语言的一个功能。 Python的其他实现不保证以这种方式工作。例如IronPython,PyPy和Jython不使用引用计数,因此不会在循环结束时关闭文件。

In your example the file isn't guaranteed to be closed before the interpreter exits. In current versions of CPython the file will be closed at the end of the for loop because CPython uses reference counting as its primary garbage collection mechanism but that's an implementation detail, not a feature of the language. Other implementations of Python aren't guaranteed to work this way. For example IronPython, PyPy, and Jython don't use reference counting and therefore won't close the file at the end of the loop.

依赖于CPython的垃圾回收实现,因为它使你的代码更加便于移植。如果您使用CPython,则可能没有资源泄漏,但如果您切换到不使用引用计数的Python实现,则需要检查所有代码并确保所有文件都已正确关闭。

It's bad practice to rely on CPython's garbage collection implementation because it makes your code less portable. You might not have resource leaks if you use CPython, but if you ever switch to a Python implementation which doesn't use reference counting you'll need to go through all your code and make sure all your files are closed properly.

在你的例子中使用:

with open("filename") as f:
     for line in f:
        # ... do stuff ...

这篇关于明确关闭文件很重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆