可能重复:
Does filehandle get closed automatically in Python after it goes out of scope?
我是python的新手。我知道如果你打开一个文件然后写它,你需要在最后关闭它。
in_file = open(from_file)
indata = in_file.read()
out_file = open(to_file, 'w')
out_file.write(indata)
out_file.close()
in_file.close()
如果我这样编写代码。
open(to_file, 'w').write(open(from_file).read())
我无法关闭它,会自动关闭吗?
答案 0 :(得分:8)
最终将关闭,但无法保证何时关闭。当你需要处理这些事情时,最好的方法是with
声明:
with open(from_file) as in_file, open(to_file, "w") as out_file:
out_file.write(in_file.read())
# Both files are guaranteed to be closed here.
另请参阅:http://preshing.com/20110920/the-python-with-statement-by-example
答案 1 :(得分:6)
Python垃圾收集器会在它破坏文件对象时自动为您关闭文件,但是您无法控制实际发生的时间(因此,更大的问题是您不知道是否文件关闭期间发生错误/异常)
preferred way to do this after Python 2.5采用with
结构:
with open("example.txt", 'r') as f:
data = f.read()
无论发生什么情况,完成后文件都会保证关闭。
答案 2 :(得分:1)
根据http://pypy.org/compat.html,CPython将关闭文件;但是PyPy只有在垃圾收集器运行时才会关闭文件。因此,出于兼容性和样式原因,最好明确关闭文件(或使用with
构造)