How to Find Path Information in Python - dummies

By John Paul Mueller

In order to use the code in a module, Python must be able to locate the module and load it into memory. The location information is stored as paths within Python. Whenever you request that Python import a module, Python looks at all the files in its list of paths to find it. The path information comes from three sources:

  • Environment variables: Python environment variables, such as PYTHONPATH, tells Python where to find modules on disk.

  • Current directory: You can change the current Python directory so that it can locate any modules used by your application.

  • Default directories: Even when you don’t define any environment variables and the current directory doesn’t yield any usable modules, Python can still find its own libraries in the set of default directories that are included as part of its own path information.

It’s helpful to know the current path information because the lack of a path can cause your application to fail. The following steps demonstrate how you can obtain path information:

  1. Open the Python Shell.

    You see the Python Shell window appear.

  2. Type import sys and press Enter.

  3. Type for p in sys.path: and press Enter.

    Python automatically indents the next line for you. The sys.path attribute always contains a listing of default paths.

  4. Type print(p) and press Enter twice.

    You see a listing of the path information. Your listing may be different, depending on your platform, the version of Python you have installed, and the Python features you have installed.


The sys.path attribute is reliable but may not always contain every path that Python can see. If you don’t see a needed path, you can always check in another place that Python looks for information. The following steps show how to perform this task:

  1. Type import os and press Enter.

  2. Type os.environ[‘PYTHONPATH’].split(os.pathsep) and press Enter.

    When you have a PYTHONPATH environment variable defined, you see a list of paths. However, if you don’t have the environment variable defined, you see an error message instead.

    The sys.path attribute doesn’t include the split() function, which is why the example uses a for loop with it. However, the os.environ[‘PYTHONPATH’] attribute does include the split() function, so you can use it to create a list of individual paths.

    You must provide split() with a value to look for in splitting a list of items. The os.pathsep constant (a variable that has one, unchangeable, defined value) defines the path separator for the current platform so that you can use the same code on any platform that supports Python.

  3. Close the Python Shell.

    The Python Shell window closes.


You can also add and remove items from sys.path.