Mahi
Mahi

Reputation: 21951

Using pathlib, parent's parent just returns the first parent itself (parent.parent == parent)

I'm trying to find the parent directory of the directory that my script is located in:

this = pathlib.Path(__name__)
parent = this.parent
parent2 = parent.parent

But printing them out shows that the second .parent isn't working:

print(this, this.absolute())
print(parent, parent.absolute())
print(parent2, parent2.absolute())
print(this.parent == this.parent.parent)

Yields the output of:

__main__ C:\Users\Markus\Projects\PathTest\bin\__main__
. C:\Users\Markus\Projects\PathTest\bin
. C:\Users\Markus\Projects\PathTest\bin
True

I'm clueless, what could be the issue?

Upvotes: 1

Views: 3163

Answers (1)

hiro protagonist
hiro protagonist

Reputation: 46921

as the printout shows: if parent = '.' then parent.parent will also be ..

try to resolve the path beforehand:

this = Path(__file__).resolve()

also note that __file__ will give you the path of your file; not __main__.

Upvotes: 3

Related Questions