How to get absolute path of python file REGARDLESS of where it is run from

1.5k views Asked by At

I'm trying to get the absolute path to a python file that I run from terminal regardless of WHERE I am in the filesystem when I run that file. So far I've looked at this, but the answers using pathlib don't work, as I'm about to demonstrate:

contents of path_test.py

import pathlib
path_ = pathlib.Path(__file__).absolute().parent
print(path_)

if you call python3 path_test.py from the same directory, or any directory above, it prints out the expected output:

/home/zaid/misc/import_test

now create a directory in the same directory mkdir dir that has path_test.py, and cd into it, now call python3 ../path_test.py

the output is:

/home/zaid/misc/import_test/dir/..

which breaks python's importlib's functionality and is NOT the expected output.

1

There are 1 answers

0
WalksB On

Solution is, from some quick testing:

import os
import pathlib
path_ = pathlib.Path(os.path.abspath(__file__))