Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does filehandle get closed automatically in Python after it goes out of scope?

Tags:

python

scope

file

If I do the following, does filehandle get closed automatically as it goes out of scope in Python:

def read_contents(file_path):   return file(file_path).read() 

If it doesn't, how can I write this function to close the scope automatically?

like image 263
bodacydo Avatar asked Mar 08 '10 20:03

bodacydo


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.

Does Python close files on exit?

Yes they do. This is a CLIB (at least in cpython) and operating system thing. When the script exits, CLIB will flush and close all file objects. Even if it doesn't (e.g., python itself crashes) the operating system closes its resources just like any other process.

Do we need to close the file after reading in 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.

What happens if you leave a file open in Python?

If you write to a file without closing, the data won't make it to the target file. But after some surfing I got to know that 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.


1 Answers

To expand on FogleBird's answer, if you do not explicitly close it then the file will be closed automatically when the file object is destroyed. In CPython this will happen as soon as there are no more references to it, e.g. if it is a local variable in a function and the function ends. However if an exception is thrown in the function and file is not explicitly closed using a with statement or a try:...finally: then a reference to the file will be kept as part of the stack trace in the traceback object and the file will not be closed, at least until the next exception is thrown.

Also IronPython and Jython use the garbage collection facilities of the .Net CLR and Java JVM respectively. These are not reference counted, so the file will remain open indefinitely until the garbage collector decides to reclaim the object's memory or the program terminates.

So in general it is important to explicitly close the file using either with: or try:...finally:.

Of course all this is holds true for any other type of object that requires explicit cleanup.

like image 132
Dave Kirby Avatar answered Oct 11 '22 22:10

Dave Kirby