Python GC也会关闭文件吗?

Does Python GC close files too?

考虑下面的一段python(2.x)代码:

1
2
for line in open('foo').readlines():
    print line.rstrip()

我假设由于打开的文件没有被引用,它必须自动关闭。我读过关于Python中的垃圾收集器的内容,它释放由未使用的对象分配的内存。gc是否足够通用以处理文件?


从码头(Python3.6):

If you’re not using the with keyword, then you should call f.close() to close the file and immediately free up any system resources used by it. If you don’t explicitly close a file, Python’s garbage collector will eventually destroy the object and close the open file for you, but the file may stay open for a while. Another risk is that different Python implementations will do this clean-up at different times.

是的,文件将自动关闭,但为了控制过程,您必须如此自行或使用with声明:

1
2
3
with open('foo') as foo_file
    for line in foo_file.readlines():
        print line.rstrip()

一次埃多克斯1〔0〕

在Python2.7公斤中,这个词是不同的:

BLCK1/

所以我认为你不应该依靠垃圾收集机自动关闭文件给你,而只是手动/使用EDOCX1〕


这取决于你做什么,检查这描述它是如何工作的。

In general I would recommend to use the context manager of the file:

ZZU1

Which is similar to(for basic understanding):

1
2
3
4
file_context_manager = open("foo","r").__enter__()
for line in file_context_manager.readlines():
    # ....
file_context_manager.__exit__()

第一个版本是一个更容易阅读的版本,而with则被称为"出口方法自动处理"(加上一位以上的上下文处理)。当with的范围偏离时,文件将自动关闭。