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

How To Solve ModuleNotFoundError in Python

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

We will discussed one by one possible reason for module not found.

We ill cover 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 no imported

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

app.py

print(math.pi)

We will get below error as a output:

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

Correct way to use math module witn in 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('http://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

The name of the module is incorrect

The other possible reason might be module name is incorrect in import. We just make sure module name is correct into 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, The python does not found named ‘matha’ module.

path of the module is incorrect

We have import module into the python application but path is not correct, we need to set correct path of 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 output as like below:

Output:

ModuleNotFoundError: No module named 'gapi'

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 *