Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is explicitly closing files important?

In Python, if you either open a file without calling close(), or close the file but not using try-finally or the "with" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:

for line in open("filename"):
    # ... do stuff ...

... is this a problem because the file can never be closed and an exception could occur that prevents it from being closed? Or will it definitely be closed at the conclusion of the for statement because the file goes out of scope?

like image 272
user553702 Avatar asked Oct 21 '22 09:10

user553702


People also ask

Why are closing files important?

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. The best defense is always to open files with a context manager.

Do we need to close file?

You never have to close File s, because it is basically a representation of a path. Only Streams and Readers/Writers. In fact, File does not even have a close() method.

What happens if you don't close a file descriptor?

As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.

Why is it important to close files and streams?

When you open a file using any programming language , that is actually a request to operating system to access the file. When such a request is made , resources are allocated by the OS. When you gracefully close those files, those resources are set free.


1 Answers

In your example the file isn't guaranteed to be closed before the interpreter exits. In current versions of CPython the file will be closed at the end of the for loop because CPython uses reference counting as its primary garbage collection mechanism but that's an implementation detail, not a feature of the language. Other implementations of Python aren't guaranteed to work this way. For example IronPython, PyPy, and Jython don't use reference counting and therefore won't close the file at the end of the loop.

It's bad practice to rely on CPython's garbage collection implementation because it makes your code less portable. You might not have resource leaks if you use CPython, but if you ever switch to a Python implementation which doesn't use reference counting you'll need to go through all your code and make sure all your files are closed properly.

For your example use:

with open("filename") as f:
     for line in f:
        # ... do stuff ...
like image 148
Peter Graham Avatar answered Oct 23 '22 21:10

Peter Graham