0
0
Pythonprogramming~5 mins

Module search path in Python

Choose your learning style9 modes available
Introduction

Python needs to know where to find the files you want to use. The module search path tells Python where to look for these files.

When you want to import a module that is not in the same folder as your program.
When you install new packages and want Python to find them automatically.
When you organize your code into different folders and want to use modules from those folders.
When debugging import errors to check where Python is looking for modules.
Syntax
Python
import sys
print(sys.path)

sys.path is a list of folder paths where Python looks for modules.

You can add new paths to sys.path to tell Python to look in other places.

Examples
This prints the list of folders Python searches for modules.
Python
import sys
print(sys.path)
This adds a new folder to the search path so Python can find modules there.
Python
import sys
sys.path.append('/my/custom/path')
print(sys.path)
This adds a folder named 'libs' from your current directory to the front of the search path.
Python
import os
import sys
sys.path.insert(0, os.path.abspath('libs'))
print(sys.path)
Sample Program

This program shows all the folders where Python looks for modules. It helps you understand where Python searches when you use import.

Python
import sys

print('Current module search paths:')
for path in sys.path:
    print(path)
OutputSuccess
Important Notes

The exact paths in sys.path depend on your Python installation and environment.

You can modify sys.path at runtime, but it only affects the current program run.

For permanent changes, you can set the PYTHONPATH environment variable before running Python.

Summary

Python uses a list of folders called the module search path to find modules when you import them.

You can see and change this list using sys.path.

Understanding the module search path helps fix import errors and organize your code better.