gpt4 book ai didi

python - Python GC 也会关闭文件吗?

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:39 25 4
gpt4 key购买 nike

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

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

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

最佳答案

更新

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

Python 3.8 docs文本已更新为:

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.

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 docs :

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()

foo_file 将在 with block 结束后关闭

Python 2.7 docs ,措辞不同:

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

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

关于python - Python GC 也会关闭文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49512990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com