Skip to main content
Python-Module-Not-Found-Error

How To Solve ModuleNotFoundError in Python

This Python tutorial helps to solve “Module Not Found Error” for python. The reasons for this error and how to solve it.

We will discuss one by one the possible reasons for the module not found.

We’ll cover the following points here:

  1. Python module is no imported
  2. Python module is not Installed
  3. The name of the module is incorrect
  4. The path of the module is incorrect

Python module is not imported

The module method has been used but forgot to include the main module, We need to import that module.

app.py

print(math.pi)

We will get the below error as an output:

Traceback (most recent call last):
  File "<string>", line 3, in <module>
NameError: name 'math' is not defined

The correct way to use the math module within app.py file:

import math
print(math.pi)

Output:

3.141592653589793

Python module is not Installed

You can get the issue when you are trying to import a module of a library which not installed in your virtual environment. So before importing a library’s module, you need to install it with the pip command.

Let’s import an module(requests) into app.py file which is not installed into our virtual environment:

r = requests.get('https://dummy.restapiexample.com/api/v1/employee/2')

print(r)

The output:

Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  ModuleNotFoundError: No module named 'requests'

Now, let’s install the library:

pip install requests

You can also checkout other Python tutorials:

The name of the module is incorrect

The other possible reason might be module name is incorrect in import. We just make sure the module name is correct in the import syntax.

For example, let’s try to import math module with extra a and see what will happen:

>>> import matha
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'matha'

As you can see above console output, Python does not found named ‘matha’ module.

path of the module is incorrect

We have imported the module into the Python application but the path is not correct, we need to set the correct path of the missed module.

Python Folder Structure:

app.py
services
---gapi.py

Let’s, we will import gapi.py as like below:

app.py

import gapi.py #incorrect

We will get the output as like below:

Output:

ModuleNotFoundError: No module named 'gapi'

The correct way to import a file into app.py:

import services.gapi.py #correct

Leave a Reply

Your email address will not be published. Required fields are marked *