Not closing os.devnull Python

Viewed 123

I was wondering if there are problems with not closing the file os.devnull in python. I am aware that normally we need to close files that we open. Nevertheless, I am wondering if it is possible to tread os.devnull as we treat sys.stdout or sys.stderr where we don't close them.

1 Answers

With normal files, you run the risk of losing data when you don't close them due to buffering. This is obviously not a concern for /dev/null.

However, while /dev/null is technically not a regular file but a device file, it uses file descriptors the same way. You can even inspect the file descriptor in Python using the fileno() method:

import os

with open(os.devnull) as devnull:
    print(devnull.fileno())

Operating systems limit the number of open file descriptors any single process can have. This is very unlikely to be a problem, but it's still good practice to treat /dev/null like any other file and close it for this reason alone.

Related