我认为
with open('file.txt','r') as f:
pass
关闭文件f,但是,我该如何证明呢?我的同事认为如果文件是开放的,它会刷新文件。
答案 0 :(得分:1)
The documentation clearly states that files will be closed once the with statement is exited.
但是,如果这还不够明确 - 这是一种你可以自己检查的方法;
Files有一个.closed
属性,您可以查看。
with open("file.txt", "r") as f:
print(f.closed) # will print False
print(f.closed) # will print True
在处理非with
方式的文件时,可以使用相同的属性。
f = open("file.txt", "r")
print(f.closed) # will print False
f.close()
print(f.closed) # will print True.
这应该作为文件确实被关闭的充分证明。