PythonGC也关闭文件吗?

2024-04-23 16:39:59 发布

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

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

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

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


Tags: 文件对象内存代码inforfooline
2条回答

这取决于你做什么,看看这个description how it works。在

一般来说,我建议使用文件的上下文管理器:

with open("foo", "r") as f:
    for line in f.readlines():
    # ....

类似于(基本理解):

^{pr2}$

第一个版本的可读性更好,with语句自动调用exit方法(再加上一点context handling)。 当with语句的作用域保留时,文件将自动关闭。在

{(取自python^.3):

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

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

一旦with块结束,foo_file将被关闭

在Python2.7docs中,措辞是不同的:

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

相关问题 更多 >