0

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.

WalksB
  • 498
  • 2
  • 14
  • 1
    `import os; os.path.abspath(__file__)` – vulpxn Oct 14 '20 at 22:51
  • this works! I've been searching for hours for a valid method. But this is only a partial solution, the full solution would do `import os; import pathlib; pathlib.Path(os.path.abspath(__file__))` to make it into a path variable to be able to take its parents. – WalksB Oct 15 '20 at 00:34

1 Answers1

0

Solution is, from some quick testing:

import os
import pathlib
path_ = pathlib.Path(os.path.abspath(__file__))
WalksB
  • 498
  • 2
  • 14