# How to Fix Python ImportError: No module named
The ImportError: No module named error occurs when Python cannot locate a module you are trying to import. This error can stem from missing packages, incorrect Python environments, or path configuration issues.
Error Patterns
Basic ImportError
Traceback (most recent call last):
File "app.py", line 1, in <module>
import requests
ImportError: No module named 'requests'ModuleNotFoundError (Python 3.6+)
Traceback (most recent call last):
File "app.py", line 2, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy'Relative Import Error
Traceback (most recent call last):
File "run.py", line 1, in <module>
from .my_module import my_function
ImportError: attempted relative import with no known parent packageSubmodule Import Error
Traceback (most recent call last):
File "app.py", line 3, in <module>
from mypackage.submodule import helper
ImportError: No module named 'mypackage.submodule'Common Causes
- 1.Package not installed - The module exists on PyPI but is not installed in your environment
- 2.Wrong Python interpreter - Package installed in one Python version, running with another
- 3.Virtual environment not activated - Installing packages globally instead of in venv
- 4.PYTHONPATH not configured - Custom modules outside standard search paths
- 5.Missing __init__.py - Directory not recognized as a Python package
- 6.Typo in module name - Simple spelling mistake in import statement
- 7.Case sensitivity - Module name case mismatch on Linux/Mac
Diagnosis Steps
Step 1: Verify Module Exists
```bash # Check if package is installed pip list | grep requests pip show requests
# Check for all Python versions python3 -m pip list python -m pip list ```
Step 2: Identify Active Python Interpreter
```bash # Which Python is running which python which python3
# Python version and path python --version python -c "import sys; print(sys.executable)" python -c "import sys; print('\n'.join(sys.path))" ```
Step 3: Check Virtual Environment
```bash # Check if venv is active echo $VIRTUAL_ENV echo $CONDA_DEFAULT_ENV
# List environments conda env list # if using conda ```
Step 4: Verify Package Installation Location
```bash # Where is the package installed? pip show requests | grep Location
# Check if it matches your Python python -c "import sys; print(sys.prefix)" ```
Solutions
Solution 1: Install Missing Package
```bash # Install package pip install requests
# Install specific version pip install requests==2.28.0
# Install from requirements pip install -r requirements.txt
# Use ensurepip if pip is missing python -m ensurepip --upgrade ```
Solution 2: Use Correct Python Interpreter
```bash # Install with specific Python version python3.11 -m pip install requests python3 -m pip install numpy
# Or use python -m pip to ensure correct interpreter python -m pip install pandas ```
Solution 3: Activate Virtual Environment
```bash # Create virtual environment python -m venv venv
# Activate (Linux/Mac) source venv/bin/activate
# Activate (Windows) venv\Scripts\activate
# Verify activation which python # Should point to venv pip install requests ```
Solution 4: Fix PYTHONPATH for Custom Modules
```bash # Add to PYTHONPATH temporarily export PYTHONPATH="${PYTHONPATH}:/path/to/your/modules"
# Or in Python code import sys sys.path.append('/path/to/your/modules') import my_module ```
```python # Better approach: Use python -m to run as module # Directory structure: # project/ # main.py # mypackage/ # __init__.py # utils.py
# Run from project root python -m main # Instead of python project/main.py ```
Solution 5: Add __init__.py for Packages
```bash # Directory structure myproject/ mypackage/ __init__.py # This file makes it a package module1.py module2.py main.py
# Create __init__.py if missing touch mypackage/__init__.py ```
# __init__.py can be empty or contain package-level imports
from .module1 import function1
from .module2 import function2Solution 6: Fix Relative Import Issues
```python # WRONG: Running script directly # python mypackage/main.py causes: # ImportError: attempted relative import with no known parent package
# RIGHT: Run as module # From project root: python -m mypackage.main ```
```python # Alternative: Use absolute imports # Instead of: from .utils import helper
# Use: from mypackage.utils import helper ```
Solution 7: Handle Case Sensitivity
```python # On Windows, this might work: import MyModule
# On Linux/Mac, it fails: # ModuleNotFoundError: No module named 'MyModule'
# Fix: Use correct case import mymodule # Check actual filename case ```
# Check actual filename case
ls -la # Linux/Mac shows exact case
dir # Windows might show different caseSolution 8: Reinstall Package
```bash # Uninstall and reinstall pip uninstall requests pip install requests
# Force reinstall pip install --force-reinstall requests
# Clear cache and reinstall pip cache purge pip install --no-cache-dir requests ```
Conda Environment Issues
```bash # List conda environments conda env list
# Activate environment conda activate myenv
# Install in conda environment conda install numpy # or pip install numpy
# Create new environment conda create -n myenv python=3.11 conda activate myenv pip install -r requirements.txt ```
Debug Import Path Issues
```python # Debug script to check import paths import sys print("Python executable:", sys.executable) print("\nPython path:") for p in sys.path: print(f" {p}")
# Check if module is importable try: import requests print(f"\nrequests location: {requests.__file__}") except ImportError as e: print(f"\nCannot import requests: {e}")
# Check pip packages from Python import subprocess result = subprocess.run(['pip', 'list'], capture_output=True, text=True) print("\nInstalled packages:") print(result.stdout) ```
Common Package-Specific Fixes
NumPy/SciPy Issues
```bash # These may need system dependencies # Ubuntu/Debian sudo apt-get install python3-dev python3-numpy python3-scipy
# macOS brew install numpy scipy
# Or use pip with specific versions pip install numpy==1.24.0 scipy==1.10.0 ```
MySQL Connector Issues
```bash # Wrong package name pip install mysql # WRONG - placeholder package
# Correct package pip install mysql-connector-python # or pip install PyMySQL ```
YAML Parser Issues
```python # Error: No module named 'yaml' pip install pyyaml # Not 'yaml'
import yaml # After installing pyyaml ```
Prevention Tips
- 1.Always use virtual environments to isolate project dependencies
- 2.Pin dependencies in requirements.txt with exact versions
- 3.Use python -m pip to ensure correct interpreter
- 4.Check PYTHONPATH if using custom module locations
- 5.Run scripts as modules when using relative imports
```bash # Generate requirements pip freeze > requirements.txt
# Reproducible install pip install -r requirements.txt ```
Related Errors
ModuleNotFoundError- Python 3.6+ version of ImportErrorImportError: cannot import name- Module found but specific name missingImportError: dynamic module does not define init function- C extension issueSystemError: Parent module not loaded- Relative import without parent package