for line in open(filename)

35

我经常看到类似以下的Python代码:

for line in open(filename):
    do_something(line)

这段代码中,什么时候会关闭filename文件?

在这种情况下,是否最好写成:

with open(filename) as f:
    for line in f.readlines():
        do_something(line)
4个回答

40
< p > filename 在作用域之外时将被关闭。这通常是方法的结尾。< /p > < p > 是的,最好使用 with。< /p >

Once you have a file object, you perform all file I/O by calling methods of this object. [...] When you are done with the file, you should finish by calling the close method on the object, to close the connection to the file:

input.close()

In short scripts, people often omit this step, as Python automatically closes the file when a file object is reclaimed during garbage collection (which in mainstream Python means the file is closed just about at once, although other important Python implementations, such as Jython and IronPython, have other, more relaxed garbage collection strategies). Nevertheless, it is good programming practice to close your files as soon as possible, and it is especially a good idea in larger programs, which otherwise may be at more risk of having excessive numbers of uselessly open files lying about. Note that try/finally is particularly well suited to ensuing that a file gets closed, even when a function terminates due to an uncaught exception.

Python Cookbook, 第59页。


1
我认为你在“filename would be closed…”中指的是 f 而不是 filename - Andrew Keeton
我的意思是,使用open(filename)创建的对象将在其超出范围时关闭,即迭代结束时。 - Esteban Küber
1
循环结束时或相关方法结束时它会被关闭吗? - foosion
取决于GC,但我相信在CPython上循环结束时它是关闭的(稍后将检查何时进行GC)。 - Esteban Küber
1
@EstebanKüber,我仍然不明白为什么使用“with”更好。似乎第一种方法也会在循环正常或异常结束时自动关闭连接。你能否再解释一下?非常感谢。 - Random Certainty

9

删除 .readlines()。对于大文件来说这是多余且不可取的(因为会消耗大量内存)。使用'with'块的变种总是关闭文件。

with open(filename) as file_:
    for line in file_:
        do_something(line)

在Python的for循环中,文件何时关闭取决于Python的实现方式。


Dex之前提到过消除readlines()。
取决于Python的实现 >> 这可能是不同的人给出不同答案的原因。
- foosion

8
< p >使用with更好,因为它会在使用后自动关闭文件。甚至不需要使用readlines(),只需使用for line in file即可。

我认为第一个示例没有关闭文件。


3

Python 是一种垃圾回收语言 - CPython 采用引用计数和备用循环检测垃圾收集器。

文件对象在被删除/终止时会关闭其文件句柄。

因此,文件最终将被关闭,并且在 CPython 中将在 for 循环结束时立即关闭。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接