What Should I do When I See “ModuleNotFoundError”?

Learn how to fix "ModuleNotFoundError" in Python. Ensure your package is installed, use the correct interpreter, and troubleshoot import errors in VS Code.

Introduction

The ModuleNotFoundError occurs when Python cannot locate the module you are trying to import. This can happen due to missing installations, incorrect paths, or virtual environment issues. This guide will help you troubleshoot and fix the error.


Step 1: Ensure the Module Is Installed

  • Check if the package is installed by running: pip list
  • If the module is missing, install it using: pip install package_name
  • Example: pip install numpy

Step 2: Verify the Correct Python Interpreter

  • Ensure that you are using the correct Python version in VS Code.
  • Press Ctrl + Shift + P (Windows/Linux) or Cmd + Shift + P (macOS) and select “Python: Select Interpreter”.
  • Choose the interpreter where your package is installed.

Step 3: Use the Correct Virtual Environment

  • If you’re working inside a virtual environment, activate it before running your script.
  • Windows (Command Prompt): venv\Scripts\activate
  • Windows (PowerShell): venv\Scripts\Activate.ps1
  • macOS/Linux: source venv/bin/activate

Step 4: Check Import Statement for Errors

  • Ensure that the import statement matches the package name exactly.
  • Example:
    # Correct
    import numpy
  • Some packages use different import names than their installation names. Example:
    # Install: pip install Pillow
    # Import:
    from PIL import Image

Step 5: Run the Script in the Correct Directory

  • Ensure that you are inside the project folder where the module is installed.
  • Use cd path/to/project to navigate before running your script.

Final Thoughts

By checking for missing installations, ensuring the correct interpreter is selected, and verifying import statements, you can resolve most ModuleNotFoundError issues.

Next Step: Learn why VS Code shows “Python not found” in the terminal and how to fix it: Why Does VS Code Show “Python Not Found” in the Terminal?

Share the Post:

Related Posts