Python Module Not Found After Pip Install

I recently installed a module using pip and got the error “Python Module Not Found.” In this tutorial, I will show you how I fixed it.

Python Module Not Found

I recently needed to use the petl library for an ETL project. I ran the usual command in my terminal:

pip install petl

The installation seemed to go smoothly, but when I tried to import the module into my script:

import petl as etl

I got the error “ModuleNotFoundError: No module named ‘petl'”.

Causes and Fixes

Through trial and error, I discovered several common reasons why this error might occur, along with their solutions.

1. Multiple Python Environments

One of the most common causes is having multiple Python environments on your machine. Each environment has its own set of installed packages. If you installed the module in one environment but are running your script in another, Python won’t find the module.

Solution: Ensure you’re using the correct environment. You can activate the environment where you installed the module:

source myenv/bin/activate  # For Unix or MacOS
myenv\Scripts\activate  # For Windows

Then, run your script again.

2. Incorrect Python Interpreter

Sometimes, your IDE or terminal might be using a different Python interpreter than the one where you installed the module.

Solution: Verify which interpreter is being used. In VSCode, you can select the interpreter by clicking on the Python version in the bottom-left corner. Ensure it matches the one where your module is installed.

You can also check the interpreter directly in the terminal:

which python
# or
which python3

3. Installing the Module in the Wrong Location

If you used sudo or installed the module globally, it might not be accessible to your user environment.

Solution: Install the module without sudo:

pip install petl

Alternatively, use the --user flag to install the module for the current user:

pip install --user petl

4. Virtual Environment Not Activated

If you’re using a virtual environment, ensure it is activated before you run your script. If not, Python will default to the global environment, which might not have the module installed.

Solution: Activate your virtual environment:

source venv/bin/activate  # For Unix or MacOS
venv\Scripts\activate  # For Windows

5. Module Name Typo

A simple typo in the module name can cause this error also.

Solution: Double-check the spelling of the module name in your import statement and the installation command.

Conclusion

In this tutorial, I have explained how to fix the ModuleNotFoundError error in Python. If the issue has not been resolved, please leave a comment below.

You may also like:

Leave a Comment