执行以下操作并且不显式处理文件对象并调用其 close()
方法是不好的做法吗?
for line in open('hello.txt'):
print line
注意 - 这适用于还没有 with
语句的 Python 版本。
我问,因为 Python 文档似乎建议这样做:-
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
这似乎比必要的更冗长。
最佳答案
在处理文件时总是需要关闭,将打开的文件句柄留在各处并不是一个好主意。当文件对象被垃圾回收时,它们最终将被关闭,但您不知道何时会关闭,同时您将通过持有不再需要的文件句柄来浪费系统资源。
如果您使用的是 Python 2.5 及更高版本,则可以使用 with
语句自动为您调用 close()
:
from __future__ import with_statement # Only needed in Python 2.5
with open("hello.txt") as f:
for line in f:
print line
这与您的代码具有相同的效果:
f = open("hello.txt")
try:
for line in f:
print line
finally:
f.close()
with
语句是对 Resource Acquisition Is Initialization 的直接语言支持。 C++中常用的成语。它允许安全使用和清理各种资源,例如它可以用于始终确保关闭数据库连接或始终释放锁,如下所示。
mylock = threading.Lock()
with mylock:
pass # do some thread safe stuff
关于python - 在 Python 文件对象上使用迭代器时是否需要 close(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1832528/