How to get the full path and directory of a Python script itself?

In a Python script, how to get the full path and directory of the Python script itself?

To get the path of the current file (the script itself), you can use __file__. To resolve any symbolic links in the path, you can use os.path.realpath(). Putting them together, you can do

os.path.realpath(__file__)

to get the full path of the Python script itself.

One example:

$ echo 'import os; print os.path.realpath(__file__)' >/tmp/test.py
$ python /tmp/test.py 
/tmp/test.py
Leave a Reply

Your email address will not be published. Required fields are marked *