In Python, I use some of my functions so often that I made a file where they are written, no matter the project I am working on. How do I tell Python to add this file to path every time my code is executed so that i can use my functions, just like adding a specific path to Pathtool in Matlab? I know in Python, I could do something like
sys.path.insert(1, 'D:/Python/FunctionDirectory')
and then from file_with_functions import my_function
but I would have to write this code to all of my projects before start coding to use my functions. I would like to always have the path to my functions added so that I can always use them like in Matlab without worrying about adding them in every single .py file.

- 119
- 8
2 Answers
you can use PYTHONPATH env var to specify folder where to look for modules
https://www.tutorialspoint.com/What-is-PYTHONPATH-environment-variable-in-Python

- 968
- 12
- 21
-
also have a look here: https://stackoverflow.com/questions/19917492/how-can-i-use-a-python-script-in-the-command-line-without-cd-ing-to-its-director – Beliaev Maksim Sep 01 '20 at 17:36
To provide complete steps for anyone with my problem for later times, I found my file with functions can be thought of as a module from which functions can be imported just like from file_with_functions import my_function
.
But, I needed to add the folder with my module to python path. Messing with environment variables in Windows didn't work for me. Fortunately here, I read about a different solution:
I simply went to my site-packages folder (to find it, import sys
then print(sys.path)
and look for a name containing the string 'site-packages'). In this folder, I created a new text file and simply pasted the path with my module there:
like this, closed the text file and changed the extension from .txt to .pth (name of file did not matter as long as it was a .pth, Python found it).

- 119
- 8