Python provides the sys.path built-in variable in order to manage Python path information. Python path information is used to specify the locations of the Python modules and related libraries. If a module is required to import and loads this path information is used. The specified paths are searched for the specified modules. The interpreter searches for new modules in the specified Python paths. The sys.path is a list that contains multiple paths as a string item.
sys.path.append() Method Syntax
The append() method is provided via the sys.path module. So in order to use the append() method the sys module should be imported. The sys.path.append() method has the following syntax.
- PATH is the new path we want to add to the Python paths.
Display Python Paths
First, we can list or print default Python paths by using the sys.path variable. First, we import the sys module and then print the sys.path which is a list type. The sys.path provides multiple items every one is a path for the Python modules.
import sys print(sys.path)
['', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/usr/local/lib/python3.8/dist-packages', '/usr/lib/python3/dist-packages']
We can see that there are multiple items and path information. The first path is ” which is an empty string. This path specifies the current working directory. This means the python module first searched in the current working directory by the Python interpreter. The path information provides the version information like python3.8 this means the current Python interpreter is versioned as 3.8.
Add New Python Path
The sys.path.append() method is used to add new Python path. New paths can be easily added to the Python path list in order to add new modules or 3rd party modules or modules developed by us. In the following example we provide the new Python path to the append() module.
import sys print(sys.path.append('/home/ismail/Python'))
If you are using the Windows operating system the Python path can be specified with the partition name or drive letter and its path. We can see that slashes are reversed and a couple of slices are used for every directory according to Linux.
import sys print(sys.path.append('C:\\Users\\ismail\\Python'))