# 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
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'requests'Common Causes
- 1.Package not installed - The module hasn't been installed in your Python environment
- 2.Wrong Python environment - Package installed in a different environment than the one running the script
- 3.Virtual environment not activated - Running script outside the virtual environment where the package is installed
- 4.Typo in module name - Simple spelling mistake in the import statement
- 5.**Missing
__init__.py** - For local modules, the package structure might be incomplete
Diagnosis Steps
Step 1: Check if the package is installed
pip list | grep requests
# or
pip show requestsStep 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
pip install requestsFor a specific version:
pip install requests==2.28.0Solution 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
# Use python -m pip to ensure installation in the current Python environment
python -m pip install requestsSolution 5: Fix local module imports
If you're importing a local module, ensure the directory structure is correct:
myproject/
├── mypackage/
│ ├── __init__.py
│ └── mymodule.py
└── main.pyIn main.py:
from mypackage import mymoduleIf __init__.py is missing, create it:
touch mypackage/__init__.pySolution 6: Add to Python path (not recommended for production)
import sys
sys.path.append('/path/to/your/module')
import your_modulePrevention Tips
- 1.Use a requirements.txt file to track dependencies:
pip freeze > requirements.txt
pip install -r requirements.txt- 1.Always activate your virtual environment before running scripts
- 2.**Use
python -m pip** instead ofpipto avoid environment confusion - 3.Use an IDE that shows import errors before runtime (VS Code, PyCharm)
Related Errors
ImportError- Module found but cannot be importedAttributeError- Module found but doesn't have the expected attribute