How to get in a python script its path ?

Published: July 13, 2021

Tags: Python; Script;

DMCA.com Protection Status

Example of how to get in a python script its path:

Getting the python script path

Let's consider a python script called test.py (located for example in the directory "/Users/mb/Desktop/test.py"). To get the python script's path a solution is to use the python module os:

import os

file_path = os.path.realpath(__file__)

print(file_path)

which will returns here:

/Users/mb/Desktop/test.py

Getting only the path without the file name

To get the path to the python script whitout the file name in it, a solution is to use "os.path.abspath":

import os

file_path = os.path.realpath(__file__)

print(os.path.abspath(__file__))

which will returns here:

/Users/mb/Desktop

References