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()
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.
这取决于你做什么,看看这个description how it works。在
一般来说,我建议使用文件的上下文管理器:
类似于(基本理解):
^{pr2}$第一个版本的可读性更好,
with
语句自动调用exit方法(再加上一点context handling)。 当with
语句的作用域保留时,文件将自动关闭。在{(取自python^.3):
所以是的,文件将自动关闭,但为了控制进程,您应该自己关闭或使用
with
语句:一旦
with
块结束,foo_file
将被关闭在Python2.7docs中,措辞是不同的:
因此,我假设您不应该依赖垃圾回收器自动关闭文件,而只需手动/使用
with
相关问题 更多 >
编程相关推荐