How to Get the Current Script File Directory in Python

Jinku Hu Feb 02, 2024
  1. Python Get the Working Directory
  2. Python Get the Script File Directory
How to Get the Current Script File Directory in Python

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.

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)

The os.path.split() method splits the file name with path to pure path and pure file name.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook