How to Fix ModuleNotFoundError in Python
In this tutorial, you'll learn about How to Fix ModuleNotFoundError in Python. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Error message: ModuleNotFoundError: No module named 'xyz'
Python raises ModuleNotFoundError when an import statement cannot find the requested module. This is one of the most common errors beginners encounter.
What Causes It
- The package isn't installed — most common cause
- Wrong Python environment — you installed in one virtualenv but run in another
- Circular imports — two modules try to import each other
- PYTHONPATH is misconfigured — Python can't find your custom modules
- The module name is misspelled — case-sensitive
Fix 1: Install the Missing Package
pip install requests
If it's already installed, upgrade:
pip install --upgrade requests
For Python 3 specifically (when both Python 2 and 3 are installed):
pip3 install requests
Fix 2: Check Your Virtual Environment
If you're using a virtual environment, activate it first:
# Create venv
python -m venv venv
# Activate (Linux/macOS)
source venv/bin/activate
# Activate (Windows)
venv\Scripts\activate
# Now install
pip install requests
Verify the module exists:
python -c "import requests; print(requests.__version__)"
Fix 3: Fix PYTHONPATH and Circular Imports
For custom modules, ensure Python can find them:
import sys
sys.path.append("/path/to/your/module")
import your_module
For circular imports, restructure your code. Instead of module_a importing module_b and vice versa, move the shared code to a third module:
# shared.py — common code both need
# module_a.py — imports from shared
# module_b.py — imports from shared
Prevention
- Always use virtual environments (
python -m venv venv) - Run
pip listto verify installed packages - Keep a
requirements.txt:pip freeze > requirements.txt - When activating a venv, check your terminal prompt shows
(venv) - For custom modules, use
pip install -e .in the project root
Quick Checklist
| Cause | Check |
|---|---|
| Not installed | pip list \| grep module_name |
| Wrong env | which python — points to your venv |
| Typo | Verify case: import numpy not import Numpy |
| Renamed package | Some pip names differ from import names (e.g., pip install Pillow → from PIL import Image) |
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro