Python GC 也会关闭文件吗?

2022-01-16 00:00:00 python file garbage-collection

问题描述

考虑以下 Python (2.x) 代码:

Consider the following piece of Python (2.x) code:

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

我假设由于打开的文件仍然未被引用,它必须自动关闭.我已经阅读了 Python 中的垃圾收集器,它释放了未使用对象分配的内存.GC 是否也足以处理文件?

I assume that since the open file remains unreferenced it has to be closed automatically. I have read about garbage collector in Python which frees memory allocated by unused objects. Is GC general enough to handle the files too?


解决方案

更新

对于当前版本的 python,明确的建议是显式关闭文件或使用 with 语句.没有任何迹象表明 GC 将为您关闭文件.所以现在的答案应该是:也许,但不能保证.始终使用 close()with 语句.

For current versions of python, the clear recommendation is to close files explicitly or use a with statement. No indication anymore that the GC will close the file for you. So now the answer should be: Maybe, but no guarantee. Always use close() or a with statement.

在 Python 3.8 文档中文本已更新为:

如果你没有使用 with 关键字,那么你应该调用 f.close() 来关闭文件并立即释放它使用的所有系统资源.

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.

警告: 调用 f.write() 而不使用 with 关键字或调用 f.close() 可能会导致参数f.write() 没有完全写入磁盘,即使程序成功退出.

Warning: Calling f.write() without using the with keyword or calling f.close() might result in the arguments of f.write() not being completely written to the disk, even if the program exits successfully.

旧答案:

取自 Python 3.6 文档:

如果你没有使用 with 关键字,那么你应该调用 f.close() 来关闭文件并立即释放它使用的所有系统资源.如果您没有明确关闭文件,Python 的垃圾收集器最终会销毁该对象并为您关闭打开的文件,但该文件可能会保持打开一段时间.另一个风险是不同的 Python 实现会在不同的时间进行这种清理.

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 语句:

So yes, the file will be closed automatically, but in order to be in control of the process you should do so yourself or use a with statement:

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

foo_file 将在 with 块结束后关闭

foo_file will be clsoed once the with block ends

在 Python 2.7 文档中,措辞不同:

当你处理完一个文件后,调用 f.close() 来关闭它并释放它打开的文件占用的任何系统资源.打电话后f.close(),尝试使用文件对象会自动失败.

When you’re done with a file, call f.close() to close it and free up any system resources taken up by the open file. After calling f.close(), attempts to use the file object will automatically fail.

所以我假设您不应该依赖垃圾收集器自动为您关闭文件,而只需手动/使用 with

so I assume that you should not depend on the garbage collector automatically closing files for you and just do it manually/use with

相关文章