Introduction
When you run a Python script, you may see:
ModuleNotFoundError: No module named 'requests'
This means Python can’t locate the module you’re trying to import.
What Is ModuleNotFoundError?
- A built-in exception raised when
import x
fails. - Indicates that
x
is not in any folder onsys.path
.
Common Causes
- Package not installed.
- Wrong virtual environment active.
- Multiple Python versions (pip vs. python mismatch).
- Naming conflicts (your script named
requests.py
). - Incorrect PYTHONPATH or broken install.
Solution 1: Install the Module
# For latest pip
python -m pip install <module_name>
# Or specify version
python -m pip install <module_name>==1.2.3
Use python -m pip
to match the interpreter you run.
Solution 2: Activate Your Virtual Environment
-
Create env (if none):
python -m venv env
-
Activate:
-
Windows (PowerShell):
.\env\Scripts\Activate.ps1
-
Git Bash:
source env/Scripts/activate
-
-
Then reinstall your package inside the env.
Solution 3: Check Python Version and Pip
Ensure you install with the same Python you run:
which python
which pip
# Or on Windows
where python
where pip
If they differ, use python -m pip install
.
Solution 4: Avoid Naming Conflicts
- Don’t name your script or folder the same as the module.
- Rename
requests.py
to avoid shadowing the real package.
Solution 5: Verify PYTHONPATH and Site-Packages
-
Inspect
sys.path
in Python:import sys print(sys.path)
- Ensure the folder containing your module is listed.
-
If using editable installs, run:
pip install -e .
Conclusion
ModuleNotFoundError
is almost always an install or path issue.
Install with the correct interpreter, activate your environment, and avoid naming collisions.
Leave a comment