Stack Overflow
Stack Overflow

Reputation: 457

Get the path of the current Python file

I am trying to the get the path of the directory of the current running file. For example, if I the following files: X/foo.py and Y/bar.py, and I am running python3 foo.py and foo.py imports bar.py, and in bar.py I get the parent directory, I want it to be Y and not X. How do I do that? currently, I get X with path = pathlib.Path(__file__).parent.resolve()

Upvotes: 0

Views: 4092

Answers (1)

Dominik Lovetinsky
Dominik Lovetinsky

Reputation: 566

This question already was answered here: Find the current directory and file's directory

What you need to do is the following:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

This will return the absolute path to the current py-file.

Upvotes: 0

Related Questions