Fix Python – Permanently adding a file path to sys.path in Python


Asked By – Shiva Krishna Bavandla

I had a file called, which I wanted to use from various other files, so I decided to add to sys.path and import this file in another file to use the file. To do so, I ran the following in IPython.

import sys

I could see the path I had just added, and when I tried to import this file from another directory path like this:

import example_file

it worked just fine, but once I came out of IPython, entered it again, and checked the sys.path, I saw that the path which I had added was not present, so how do I add a path to sys.path permanently in Python?

Now we will see solution for issue: Permanently adding a file path to sys.path in Python


There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can’t “add a file to sys.path“. You always add its directory and then you can import the file.

This question is answered By – BrenBarn

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0