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.
Solution is, from some quick testing: