Python GC也会关闭文件吗? [英] Does Python GC close files too?
问题描述
请考虑以下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?
推荐答案
来自 docs (python 3.6):
Taken from the docs (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()
一旦with
块结束,
foo_file
将被清除
foo_file
will be clsoed once the with
block ends
在python 2.7 docs 中,措辞有所不同:>
In the python 2.7 docs, the wording is different:
使用完文件后,请调用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
这篇关于Python GC也会关闭文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!