I think that
with open('file.txt','r') as f:
pass
closes file f, but, how can I prove it? My colleague thinks it will flush the file if it is open for writing.
I think that
with open('file.txt','r') as f:
pass
closes file f, but, how can I prove it? My colleague thinks it will flush the file if it is open for writing.
The documentation clearly states that files will be closed once the with statement is exited.
However, if that is not proof enough - here is a way you can check for yourself;
Files have a .closed
property that you can check.
with open("file.txt", "r") as f:
print(f.closed) # will print False
print(f.closed) # will print True
The same property can be used when dealing with files the non-with
way.
f = open("file.txt", "r")
print(f.closed) # will print False
f.close()
print(f.closed) # will print True.
This should service as sufficient proof that the file is indeed being closed.