I have read that it is important to call close()
on a file which has been opened with open(filename, 'w'|'a')
because otherwise changes made to the opened file may not be persisted. I believe this is due to buffering.
My understanding is that the GC mechanism cannot be relied on to properly close an opened file, because this is not portable across different Python interpreters.
I also understand that a close equivalent of RAII is implemented using contexts.
For example, the following with
context automatically calls close()
when the scope of the with
statement ends.
with open(filename, 'w') as ofile:
# pass
# ofile.close() called automatically (literally, or effectively?)
Does the situation change if after every call to .write()
, we follow up with a call to .flush()
? In this context, is it still necessary/important/advisable (delete as appropriate) to also explicitly call .close()
rather than leaving the open file to be garbage collected later?
1
If you don’t close a file “handle” either explicitly or implicitly (work manager) then you could exhaust the number of allowed open files on your system. For example, the soft limit on MacOS is 1,024. Flushing the file will help to maintain the file’s integrity (on disk) but the file remains open as far as Python (and the underlying OS) is concerned
2