How to get the path where the current script you're running lives?#
sys.path[0]returns the path of the script that launched the python interpreter. If you can this script directly, it will return the path of the script. If the script however, was imported from another script, it will return the path of that script.
Import a file from a directory#
Simple#
To import general.py
import sys sys.path.append('../somedir') from general import somefunction
Better#
You may want to execute the script from any arbitrary path.
import sys sys.path.append(os.path.abspath(os.path.join(sys.path[0], '..', 'somedir'))) from general import somefunction
Proper#
The Better script will work in situations where the script is called from the shell. If it called from another python script, it may not work.
Python - Fixme