如果您使用'with'语句打开文件,是否仍需要关闭文件对象? [英] If you're opening a file using the 'with' statement, do you still need to close the file object?

查看:315
本文介绍了如果您使用'with'语句打开文件,是否仍需要关闭文件对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于打开文件,我习惯了显然较旧的语法:

For opening files, I'm used to the apparently older syntax:

f = open("sub_ranks.txt","r+")
for line in f:
    ...
f.close()

我被告知现在使用这种语法几次..

I've been told to use this syntax instead a couple of times now..

with open("sub_ranks.txt", "r+") as f:
    for line in f:
        ...

当使用with语句时,第二个例子中仍然需要一个文件对象close语句吗?

Is a file object "close" statement still needed in the second example, when the "with" statement is being used?

如果是这样,是否有任何具体的理由使用with语句进行文件读取?在这种情况下,它(稍微)更详细。

And if so, is there any concrete reason to use the "with" statement for file reading? In this case, it's (slightly) more verbose.

推荐答案

您当前问题的答案是否。带有块的确保当控件离开块时文件将被关闭,无论出于何种原因,包括异常(好吧,排除某人将电源线拉到计算机上并且其他一些罕见的事件。)

The answer to your immediate question is "No". The with block ensures that the file will be closed when control leaves the block, for whatever reason that happens, including exceptions (well, excluding someone yanking the power cord to your computer and some other rare events).

所以最好使用带块的

So it's good practice to use a with block.

现在可以说,打开一个文件只是为了阅读然后无法关闭它不是 大部分问题。当垃圾收集到来时(无论何时可能),如果没有对它的引用,该文件也将被关闭;最迟将在您的程序退出时发生。实际上,官方文档中的几个代码示例忽略了关闭仅为读取访问而打开的文件。在编写文件或使用示例中的读取加模式时,您肯定需要关闭该文件。由于未能正确关闭文件,她在SO上处理不完整/损坏的文件有很多问题。

Now arguably, having opened a file only for reading and then failing to close it is not that much of a problem. When garbage collection comes around (whenever that may be), that file will be closed, too, if there are no references to it anymore; at the latest that will happen when your program exits. In fact, several code samples in the official docs neglect closing a file that has been opened only for read access. When writing a file or when using the "read plus" mode like in your example, you definitely need to close the file. There are many questions her on SO dealing with incomplete/corrupted files because of a failure to close them properly.

这篇关于如果您使用'with'语句打开文件,是否仍需要关闭文件对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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