PromptHub
Python Beginner 14 views

Python ModuleNotFoundError

Python cannot find the specified module in the installed packages or system path.

Explanation

ModuleNotFoundError was introduced in Python 3.6 and occurs when Python cannot locate a module that is imported in the code. Unlike ImportError which can occur during module loading, ModuleNotFoundError specifically means the module was not found at all. Common causes include the package not being installed, the wrong Python interpreter being used, virtual environment not activated, typos in the module name, or the package having a different import name than its pip name.

Common Causes

  • Package not installed
  • Virtual environment not activated
  • Wrong Python interpreter
  • Package name mismatch (pip vs import)
  • Module in non-standard path

Solution

Install the missing module using pip: pip install package_name. Verify you're using the correct Python interpreter and virtual environment. Check that the package name in the import statement matches the installed package name (some packages have different names, like Pillow imports as PIL). Use pip list to see installed packages. Ensure the module is in the Python path by checking sys.path.

Code Example

import requests  # ModuleNotFoundError if not installed

# Fix: install the module
# pip install requests

# Common mismatch: pip name vs import name
# pip install Pillow  -->  import PIL
# pip install scikit-learn  -->  import sklearn
# pip install python-dateutil  -->  import dateutil

# Check installed packages
import subprocess
subprocess.run(['pip', 'list'])

# Verify Python environment
import sys
print(sys.executable)  # shows which Python is being used
print(sys.path)  # shows module search paths

# Using virtual environment correctly
# python -m venv venv
# source venv/bin/activate  (Linux/Mac)
# venv\Scripts\activate  (Windows)
# pip install requests

Error Information

Language

python

Difficulty

Beginner

Views

14

Related Errors