Computer Science · Ch 2 — File Handling in Python
Closing a file
Closing a file
Once a file has been opened and you have finished reading from it or writing to it, you must close it. Closing a file is a good programming practice because it tells the operating system that you are done with that resource. Python provides the close() method specifically for this purpose.
When you close a file, the system frees the memory that was allocated to hold the file object. More importantly, Python ensures that any data you have written but which has not yet been physically saved to the disk — called unwritten or unsaved data — is flushed off (written) to the file before the file is actually closed. This means that if your program crashes after a write operation but before the file is closed, you could lose data. Therefore, it is always advised to close the file as soon as your work with it is complete.
The syntax of the close() method is straightforward:
file_object.close()
Here, file_object is the object that was returned when you opened the file using the open() function. For example, if you opened a file with f = open('data.txt', 'r'), then you would close it with f.close(). …