Skip to content
Home » Path Searching of a Module

Path Searching of a Module


Path Searching of a Module in Python

When you import a module in Python—like:

import math
import mymodule

Python must locate the module file.
The process through which Python searches for modules is called the Module Search Path.

Python follows a specific order to find modules, defined by the module search path list, stored in:

sys.path

How Python Searches for a Module (Order of Search)

Python searches for a module in the following sequence:


1️⃣ Current Working Directory (CWD)

Python first looks for the module in the directory from where your program is running.

Example:
If your file main.py and mymodule.py are in the same folder:

project/
   main.py
   mymodule.py

Then:

import mymodule

Python finds it instantly.


2️⃣ PYTHONPATH Environment Variable

If the module isn’t found in CWD, Python checks PYTHONPATH, which is an environment variable containing extra module directories.

To view PYTHONPATH:

import os
print(os.environ.get("PYTHONPATH"))

You can add custom directories here.


3️⃣ Standard Library Directories

Python checks the folders where built-in modules are stored.

Example modules found here:

  • math
  • os
  • random
  • datetime

These are installed with Python itself.


4️⃣ Site-packages Directory (Third-party Modules)

Python next checks the directory where external modules (installed via pip) are stored.

Example:

  • numpy
  • pandas
  • requests
  • matplotlib

Typically located at:

C:\Python\Lib\site-packages\

or in Linux:

/usr/local/lib/python3.x/site-packages/

5️⃣ Built-in Module Registry

Finally, Python checks its built-in module dictionary for modules written in C.

Examples:

  • sys
  • time
  • itertools

If still not found:
👉 Python raises ModuleNotFoundError


Viewing Python’s Module Search Path

Use:

import sys
print(sys.path)

This prints a list of directories that Python searches for modules.

Example Output:

[
 'C:\\Users\\User\\Project',
 'C:\\Python39\\python39.zip',
 'C:\\Python39\\DLLs',
 'C:\\Python39\\lib',
 'C:\\Python39',
 'C:\\Python39\\lib\\site-packages'
]

Modifying Module Search Path at Runtime

You can manually add a folder to the path:

import sys
sys.path.append("C:/myfolder")

Now Python will search this folder too.


Why Understanding Module Search Path Is Important?

✔ Helps solve ModuleNotFoundError
✔ Required when using custom modules
✔ Useful when installing third-party libraries
✔ Helps organize large Python projects
✔ Required for interview & university exams


Exam-Ready Answer (Short Form)

Python searches for a module using the module search path defined in sys.path. The search order is: (1) Current Working Directory, (2) PYTHONPATH environment variable, (3) Standard Library directories, (4) Site-packages, and (5) Built-in module registry. If the module is not found in any of these, Python raises ModuleNotFoundError.