Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python close files that have been gc'ed?

I had always assumed that a file would leak if it was opened without being closed, but I just verified that if I enter the following lines of code, the file will close:

>>> f = open('somefile.txt')
>>> del f

Just out of sheer curiosity, how does this work? I notice that file doesn't include a __del__ method.

like image 886
Jason Baker Avatar asked Feb 22 '09 17:02

Jason Baker


People also ask

Does Python close files automatically?

Within the block of code opened by “with”, our file is open, and can be read from freely. However, once Python exits from the “with” block, the file is automatically closed.

How do you make sure a file is closed after using it Python?

You can use the with statement to open the file, which will ensure that the file is closed. See http://www.python.org/dev/peps/pep-0343/ for more details.

What happens when you close a file in Python?

The close() method of a file object flushes any unwritten information and closes the file object, after which no more writing can be done. Python automatically closes a file when the reference object of a file is reassigned to another file. It is a good practice to use the close() method to close a file.

Do you have to close file when using with Python?

You've learned why it's important to close files in Python. Because files are limited resources managed by the operating system, making sure files are closed after use will protect against hard-to-debug issues like running out of file handles or experiencing corrupted data.


1 Answers

In CPython, at least, files are closed when the file object is deallocated. See the file_dealloc function in Objects/fileobject.c in the CPython source. Dealloc methods are sort-of like __del__ for C types, except without some of the problems inherent to __del__.

like image 100
habnabit Avatar answered Oct 08 '22 13:10

habnabit