Is closing a file after having opened it with `open()` required in Python? [closed]
Regarding my previous question, I noticed that in both answers that used the open()
function, there was no mention of closing the file.
I've read that it's good practice to do so, but is there actually any need for it? Is it just unnecessary code?
Does the file get closed automatically?
When do files get closed?
As we can learn from Is explicitly closing files important? (StackOverflow), the Python interpreter closes the file in the following cases:
- you manually invoke the
close()
method of afile
object explicitly or implicitly by leaving awith open(...):
block. This works of course always and on any Python implementation. - the
file
object's last reference got removed and therefore the object gets processed by the Garbage Collector. This is not a language feature, but a special feature of the CPython implementation only, so for portability don't rely on this! - the Python interpreter terminates. In this case it should close all file handles that got opened. Some older versions of Python3 would have also printed a warning that you should have closed them manually yourself. However, imagine a crash or you force-killing the Python interpreter and you will see that this is also not reliable.
So only the first (manual) method is reliable!
What would happen if a file stays open?
First, depending on the implementation of your Python interpreter, if you opened a file with write access, you can not be sure that your modifications got flushed to the disk until you either manually induce it or the file handler gets closed.
Second, you may only open a limited number of files on your system per user. If you exceed this limit by e.g. opening many files in a loop in your Python program without closing them as soon as possible, the system may refuse to open further file handles for you and you'll receive an exception. It may also happen that your program takes the last allowed open file and another program will fail because it gets declined.
Third, open files on a removable device prevent it from getting unmounted or ejected. You may still delete the file on some file systems like ext4
, where simply the file descriptor/hard link to the file's inode gets removed/unlinked but the program which opened the file may still access the inode through its own temporary file handler. This is e.g. also the mechanism that allows you to update packages while the respective software is running. However, e.g. NTFS has no such feature. It may however never get modified by two concurrent processes, so it will be still somehow blocked for others.