The error message:
ModuleNotFoundError: No module named 'xyz'
occurs when Python cannot find the module xyz because:
- The module is not installed.
- The module name is misspelled.
- The module is not in the correct environment.
- There is a conflict with another file name in the project.
1. Causes and Solutions
Cause 1: The Module is Not Installed
If the module is an external package (like numpy
, pandas
, etc.), it must be installed separately.
Incorrect Code:
import numpy # If 'numpy' is not installed
Error Output:
ModuleNotFoundError: No module named 'numpy'
Solution: Install the Missing Module
Run the following command in the terminal or command prompt:
pip install numpy
If using Jupyter Notebook, run:
!pip install numpy
If using conda, run:
conda install numpy
Cause 2: Incorrect Module Name or Typo
Python module names are case-sensitive and should be spelled correctly.
Incorrect Code:
import Pandas # Wrong capitalization
Error Output:
ModuleNotFoundError: No module named 'Pandas'
Solution: Use the Correct Module Name
import pandas # Correct spelling and case
Cause 3: Using the Wrong Python Environment
If a package is installed in a different Python environment, Python cannot find it.
Solution: Check Your Python Version and Environment
- Check the Python version where the module is installed:
python -m pip show numpy
- If you are using a virtual environment, activate it first:
source venv/bin/activate # macOS/Linux venv\Scripts\activate # Windows
Then install the package: shCopyEditpip install numpy
Cause 4: The Module is Not in the Correct Directory
If you created a custom module (xyz.py
), Python must know where to find it.
Incorrect Code:
import mymodule # If 'mymodule.py' is not in the project folder
Solution: Add the Module Path
import sys
sys.path.append('/path/to/module') # Add the correct path
import mymodule
Cause 5: File Name Conflict
If your script is named the same as a module, Python might import your script instead.
Incorrect Scenario:
- Your file is named math.py.
- You try to import Python’s built-in
math
module. - Python loads your
math.py
file instead, causing an error.
Solution: Rename Your Script
- Rename
math.py
to something else, likemath_util.py
. - Delete any
__pycache__
folders.
2. Best Practices to Avoid ModuleNotFoundError
Install missing modules using pip install module_name
Use the correct spelling and capitalization
Check your Python environment and virtual environments
Avoid naming files the same as modules
Use sys.path.append()
if importing a custom module