How to get the directory path of a Python 3 script from within itself
One of the best way to reference files in Python scripts is to based the file path on the directory where the Python script resides in. This will allow us to always reference our files correctly no matter where our Python script is being executed.
This post documents the Python 3 code that I often used to get the directory path of a Python 3 script from within itself.
Python 3 code to get the directory path of the running script
To get the directory path of a Python 3 script, I will typically write the following code:
import os scriptDirectory = os.path.dirname(os.path.realpath(__file__))
I will first import the
os module. With the
os module imported, I can then use the
realpath function of the
os.path module on the
__file__ attribute to get the file path of the current Python 3 script. I then use the
dirname function to get the directory where the current Python 3 script resides on.