Python Module Search Path

Created with Sketch.

Python Module Search Path

Summary: in this tutorial, you’ll learn how the module search path works in Python when you import a module into a program.

Introduction to Python module search path

When you import a module in a program:

import module

Code language: Python (python)

Python will search for the file from the following sources:

  • The current folder from which the program executes.
  • A list of folders specified in the PYTHONPATH environment variable, if you set it before.
  • An installation-dependent list of folders that you configured when you installed Python.

Python stores the resulting search path in the sys.path variable that comes from the sys module.

The following program shows the current module search path:

import sys

for path in sys.path:

Code language: Python (python)

Here’s a sample output on Windows:

C:\Program Files\Python38\
C:\Program Files\Python38\DLLs
C:\Program Files\Python38\lib
C:\Program Files\Python38
C:\Program Files\Python38\lib\site-packages

Code language: Shell Session (shell)

And the following is the sample output on Linux:


Code language: Shell Session (shell)

To make sure Python can always find the, you need to:

  • Place in the folder where the program will execute.
  • Include the folder that contains the in the PYTHONPATH environment variable. Or you can place the in one of the folders included in the PYTHONPATH variable.
  • Place the in one of the installation-dependent folders.

Modifying the Python module search path at runtime

Python allows you to modify the module search path at runtime by modifying the sys.path variable. This allows you to store module files in any folder of your choice.

Since the sys.path is a list, you can append a search-path to it.

The following example adds the d:\modules to the search path and use the recruitment module stored in this folder:

>>> import sys
>>> sys.path.append('d:\\modules\\')
>>> import recruitment
>>> recruitment.hire()
Hire a new employee...

Code language: JavaScript (javascript)


  • When you import a module, Python will search for the module file from the folders specified in the sys.path variable.
  • Python allows you to modify the module search path by changing, adding, and removing elements from the sys.path variable.

Leave a Reply

Your email address will not be published. Required fields are marked *