# How to Fix Python ModuleNotFoundError

The ModuleNotFoundError is one of the most common errors Python developers encounter. This guide will help you understand why it happens and how to fix it.

Error Pattern

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

Common Causes

  1. 1.Package not installed - The module hasn't been installed in your Python environment
  2. 2.Wrong Python environment - Package installed in a different environment than the one running the script
  3. 3.Virtual environment not activated - Running script outside the virtual environment where the package is installed
  4. 4.Typo in module name - Simple spelling mistake in the import statement
  5. 5.**Missing __init__.py** - For local modules, the package structure might be incomplete

Diagnosis Steps

Step 1: Check if the package is installed

bash
pip list | grep requests
# or
pip show requests

Step 2: Verify your Python environment

```bash # Check which Python is being used which python which pip

# Verify they're from the same environment python -m pip list ```

Step 3: Check virtual environment status

```bash # Check if a virtual environment is active echo $VIRTUAL_ENV

# On Windows echo %VIRTUAL_ENV% ```

Solutions

Solution 1: Install the missing package

bash
pip install requests

For a specific version:

bash
pip install requests==2.28.0

Solution 2: Activate your virtual environment

```bash # On Linux/macOS source venv/bin/activate

# On Windows venv\Scripts\activate ```

Solution 3: Use the correct Python interpreter

```bash # Use the Python from your virtual environment directly ./venv/bin/python your_script.py

# On Windows .\venv\Scripts\python.exe your_script.py ```

Solution 4: Install in the correct environment

bash
# Use python -m pip to ensure installation in the current Python environment
python -m pip install requests

Solution 5: Fix local module imports

If you're importing a local module, ensure the directory structure is correct:

bash
myproject/
├── mypackage/
│   ├── __init__.py
│   └── mymodule.py
└── main.py

In main.py:

python
from mypackage import mymodule

If __init__.py is missing, create it:

bash
touch mypackage/__init__.py

Solution 6: Add to Python path (not recommended for production)

python
import sys
sys.path.append('/path/to/your/module')
import your_module

Prevention Tips

  1. 1.Use a requirements.txt file to track dependencies:
bash
pip freeze > requirements.txt
pip install -r requirements.txt
  1. 1.Always activate your virtual environment before running scripts
  2. 2.**Use python -m pip** instead of pip to avoid environment confusion
  3. 3.Use an IDE that shows import errors before runtime (VS Code, PyCharm)
  • ImportError - Module found but cannot be imported
  • AttributeError - Module found but doesn't have the expected attribute