Fix Python ModuleNotFoundError: No module named X
Python raises ModuleNotFoundError when an import statement fails because the module is missing, not installed, or not in the Python path. This guide covers diagnosis and resolution.
Symptoms
You run a Python script and see an error like:
ModuleNotFoundError: No module named 'requests'This halts execution immediately. The error may occur for built-in modules, third-party packages, or your own local modules.
Root Causes
- Module not installed – The package is missing from the current Python environment.
- Wrong Python interpreter – You installed the module for a different Python version or virtual environment.
- PYTHONPATH misconfiguration – Python cannot find the module’s location.
- Circular imports or naming conflicts – Your script shares a name with a standard library module (e.g.,
math.py). - Incomplete installation – The package failed to install properly.
Step-by-Step Fix
1. Verify the module name and spelling
Check for typos. Module names are case-sensitive. For example, import numpy works, but import Numpy does not.
2. Install the missing module
Use pip to install the package. Open a terminal (or command prompt) and run:
pip install requestsIf you are using Python 3 specifically, use pip3:
pip3 install requests3. Check your Python environment
Ensure you are using the same Python interpreter where the module was installed. Run:
which python # macOS/Linux
where python # WindowsThen check installed packages:
pip listIf the module is not listed, you are likely in a different environment.
4. Activate the correct virtual environment
If you use virtual environments, activate it before running your script:
source venv/bin/activate # macOS/Linux
venv\Scripts\activate # WindowsThen install the package inside the environment.
5. Update PYTHONPATH (for local modules)
If the module is a local file, add its directory to sys.path at the top of your script:
import sys
sys.path.append('/path/to/your/module')
import your_moduleAlternatively, set the PYTHONPATH environment variable.
6. Reinstall the module
Sometimes a partial installation causes the error. Reinstall with:
pip uninstall requests
pip install requestsAlternative Fixes
- Use a requirements file – Run
pip install -r requirements.txtto install all dependencies at once. - Install for the user only – Add
--userflag:pip install --user requests. - Use conda – If you use Anaconda, try
conda install requests. - Check for naming conflicts – Rename your script if it matches a standard library module (e.g., rename
math.pytomy_math.py).
Prevention
- Always use virtual environments for project isolation.
- Maintain a
requirements.txtfile with exact versions. - Run
pip freeze > requirements.txtafter installing packages. - Use an IDE that shows the active Python interpreter.
- Test imports in a fresh environment before deploying.
By following these steps, you can quickly resolve the ModuleNotFoundError and prevent it from recurring.
Was this solution helpful?