-2

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.

James
  • 32,991
  • 4
  • 47
  • 70
silvermangb
  • 355
  • 2
  • 11

1 Answers1

1

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.

Shadow
  • 8,749
  • 4
  • 47
  • 57
  • 1
    Yes: close implies flush. See https://stackoverflow.com/questions/2447143/does-close-imply-flush-in-python – Shadow Nov 02 '17 at 02:06