如果要使用“with”语句打开文件,是否仍需要关闭文件对象?

2024-03-28 15:12:24 发布

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

打开文件时,我习惯了明显较旧的语法:

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

我已经被告知使用这种语法,而不是现在的几次。。

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

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

如果是的话,是否有任何具体的理由使用“with”语句来读取文件?在这种情况下,它(稍微)更加冗长。


Tags: 文件对象intxtforcloseaswith
3条回答

没有

假设要按如下方式打印主机名:

with open("/etc/hostname","r") as f: print f.read() 

它将打开文件,执行其工作,然后关闭文件。

你现在的问题的答案是“不”。with块确保当控件离开块时文件将被关闭,无论发生什么原因,包括异常(好吧,排除有人将电源线拉到您的计算机和其他一些罕见事件)。

因此,最好使用with块。

现在可以说,打开一个文件只是为了读取,但却无法关闭它,这并不是一个大问题。当垃圾回收出现时(无论何时),如果不再有对它的引用,该文件也将被关闭;最迟将在程序退出时关闭。事实上,官方文档中的几个代码示例忽略了关闭仅为读取访问而打开的文件。在编写文件或使用“read plus”模式(如示例中所示)时,您肯定需要关闭该文件。由于无法正确关闭不完整/损坏的文件,她在处理这些文件时遇到了许多问题。

从python文档中,我看到with是try/finally块的语法糖。 所以

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

没有

从Python文档:

The ‘with‘ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The ‘with‘ statement is a control-flow structure whose basic structure is:

with expression [as variable]: with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has enter() and exit() methods).

Here是另一篇清楚的文章。

相关问题 更多 >