Get the Current Script File Directory in Python

  1. Python Get the Working Directory
  2. Python Get the Script File Directory

We have introduced 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
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.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.