The ModuleNotFoundError occurs when a Python module or package that's being imported can't be located within the system directory tree by the interpreter.

The exception is a subclass of the ImportError exception .

print(issubclass(ModuleNotFoundError, ImportError))
import matth

The exception can be raised when using the import statement(as in above) as well as when using the __import__() function.

__import__("mathh")

Causes of the ModuleNotFoundError

  • The module name is Incorrectly spelled.
  • The file path of the module may be incorrect.
  • The module may not be installed on your system.
  • PYTHONPATH is not set correctly: If the PYTHONPATH environment variable is not set to include the directory containing the module, the ModuleNotFoundError will be thrown.
  • Multiple Python installations: If you have multiple versions of Python installed, you may be running the wrong version for the module.
  • Insufficient permissions: If you do not have permissions to access or modify the module, you will get the ModuleNotFoundError.

Handling the ModuleNotFoundError

You should first ensure that the module name is correctly spelled during import. If that is not the issue, you can follow the steps outlined below.

  1. First check that the module or component is properly installed.
  2. Verify that the module’s name is correct and that it is located in one of the search paths listed in sys.path.
  3. If the module is installed correctly but Python still cannot find it, try adding the path to the module to the sys.path list manually. We will see how to do this in a while.
  4. You can also add the module's directory to PYTHONPATH using your operating system settings panel.

add a directory to Python Path using sys module.

The builtin sys module contain a list of all the directories in the Python path  which is used to specify where Python will look for available modules when importing.

import sys 

print(sys.path)

We can use the sys.path.append() function to  and a directory to the Python path . This effectively makes it possible to import a python file from the added directory.

sys.path.append('/path/to/module')