How To/python/

Paths to scripts in python

Current Working Dir

os.getcwd() returns string that contains absolute path to current working dir. That is dir from which you are calling python script!

sys.path[0] contains path to current script - no matters from which dir you are calling it!

Script path: /home/usr/a/b/c.py

# c.py content:
import os, sys
print "os.getcwd(): %s" % os.getcwd()
print "sys.path[0]: %s" % sys.path[0]

From /home/usr/ run command: @$ python a/b/c.py@. Output:

$ os.getcwd(): /home/usr
$ sys.path[0]: /home/usr/a/b

Absolute path to current module

To get absolute path to current script (even if it is imported module) use:

os.path.dirname(os.path.realpath(__file__))