본문 바로가기

Language/Python

[sys] The way to import module not found

1. Using sys.path

The Python sys.path is a list of directories where the Python interpreter searches for modules. When a module is claimed in a project file, it will search through each one of the directories in the list.

 

So, we can easily load Python files in any directory by modifying element of sys.path.

 

1.1 Check a list of sys.path

import sys
print(sys.path)

 

1.2 Append directories to sys.path

sys.path.append() method can append any directories in the sys.path list. If we add a path to this list, we can import the Python file or modules in that path into the import statement.

 

import sys
sys.path.append('../../dir1/module.py')

 

2. Change PYTHONPATH

Another way of loading files is modifying PYTHONPATH environment variable. PYTHONPATH is an environment variable which we can set to add additional directories where Python will look for modules and packages.

 

By adding directories to PYTHONPATH, we can add module and files outside of Python code.

 

 

 

Source from :