How to Get the Current Script File Directory

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.

Get script file path.py
import os

wd = os.getcwd()
print("working directory is ", wd)

filePath = __file__
print("This script file path is ", filePath)

absFilePath = os.path.abspath(__file__)
print("This script absolute path is ", absFilePath)

path, filename = os.path.split(absFilePath)
print("Script file path is {}, filename is {}".format(path, filename))
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.