Debug IOError: [Errno 9] Bad File Descriptor in os.system()

What Can Lead To IO Error [Errno 9] Bad File Descriptor During Os System()

The os or the operating system module is used to interact with the operating system via python code. This module doesn’t need any special installation as it comes pre installed with python. You can access system files through the os module, use command line code, directories and file systems and even manipulating environment variables.

An input output error or an IO error occurs when the program or the code is unable to access the required files or directories via the operating system. The interpreter might also raise this error when there is an incorrect file name or if the location is wrong.

The IOError: [Errno 9] Bad File Descriptor in Python occurs when we attempt to access a file using os.system(), but the file is already open elsewhere and has not been properly closed. This error can be prevented by ensuring that files are properly closed after use. Always close a file using the native close method before attempting to open it again or manipulate it using the os module.

Understanding I/O Errors in Python

An Input/Output (I/O) error occurs when a program or code cannot access the necessary files or directories via the operating system. This can happen due to incorrect file names, erroneous file locations, or files that have been improperly opened or closed

An I/O error is a runtime error that is, the exception is raised when the code is executed. Now, if we try to open() a file which is not located at the given path or doesn’t exist, it will raise an I/O error. This can also happen if you provide a wrong extension at the end of a file. For example, if we try to open a csv file with the extension “.txt”, it will result in this exception.

Since this error cannot be fixed just by looking at the syntax of a code, it is a type of runtime error raised only during execution.

An example of an I/O error is given below where we try to open a file called “sample.txt” using f=open("sample1.docx",'r'), but there exists no file as such.

IOError: [Errno 2] No such file or directory: 'sample1.docx'

Note: In some IDEs this error might also be displayed as FileNotFound error which in itself tells that there exists no file as the one specified in the code. This doesn’t negate the fact that this is still an I/O error.

Exploring the Versatility of Python’s os Module

The os module or the operating system contains many different functions which helps the python code to interact with the system files. It is very easy to use and makes the processing of opening and reading files efficient. You can also easily write new data into existing or new files via the os module.

You can also access file systems, file hierarchies, environment variables, etc. through the os module. Also command line arguments can be accessed via the same library.

All you need to do to access this module is use the import statement in your code and you’ll be able to access everything to interact your operating system with as follows:

import os

Related: Python os module – 10 Must-Know Functions.

Exploring the Causes and Fixes for IOError: [Errno 9] Bad File Descriptor

The main cause of this error is because you didn’t close the file using the file.close() method. For example, suppose you have opened a file using open() and then you’re trying to access it via the os.system() module for doing other programs that can’t be done when the file is already opened somewhere else.

Since the file is closed somewhere else and not closed using the close() function, it raises error no.9 . Now, if you try to delete the contents of the file, the file.__del__ destructor is called which cannot do it’s job until it can make sure that the file is closed. The error looks like this:

import os
fl = open("sample.txt", 'r')
os.close(fl.fileno())
del fl

In this code snippet, we attempt to close a file through the os module’s close function when it is already opened elsewhere. Because it is not closed using the file’s native close method, the interpreter raises an IOError: [Errno 9] Bad File Descriptor.

close failed in file object destructor:
IOError: [Errno 9] Bad file descriptor

The os.close() is trying to close a file through the operator when it is already opened somewhere else but since it is not being closed using the close() keyword, the interpreter raises this error.

Causes Of An IO Error
Causes Of An IO Error

The most effective way to avoid this error is to ensure that files are properly closed after use. In the example below, we open a file, close it, and then open it again in a different mode to add data.

f1=open('sample.txt','r')
# Ensure the file is closed before accessing it again
f1.close()
f2=open('sample.txt','a')
del f2

Or the other fix is using a try and except block for exception handling like we do with other errors as well.

import os
try:
    fl = open("sample.txt", 'r')
    os.close(fl.fileno())
    del fl
except IOError:
    print("Error occurred! Make sure the file is properly closed.")

Check out: Handling Built-in Exception IOError in Python (With Examples)

Summary

Today, we’ve demystified the IOError: [Errno 9] Bad File Descriptor in Python and examined how to effectively handle files to prevent it. Remember, proper file handling is key to avoiding a plethora of errors, including this one. Can you think of any other scenarios where improper file handling could lead to errors?