We talk about the file and directory operation in Python 3 basic tutorial. In this section, we show you how to get the relative and absolute path of the executing script.
Python get the working directory
os.getcwd() function returns the current working directory.
If you run it in Python idle prompt, the result is the path of Python IDLE.
Python get the script file directory
The script file path could be found in the global namespace with the special global variable
__file__. It returns the relative path of the script file relative to the working directory.
We will show you in the below example codes how to use the functions we just introduced.
absFilePath = os.path.abspath(__file__)
os.path.abspath(__file__) returns the absolute path of the given relative path.
path, filename = os.path.split(absFilePath)
os.path.split() function splits the file name with path to pure path and pure file name.