Search code examples
pythonpathlib

Why is pathlib.Path(__file__).parent.parent sensitive to my working directory?


I have a script that's two directories down.

❯ tree
.
└── foo
    └── bar
        └── test.py
❯ cd foo/bar
❯ cat test.py

    from pathlib import Path
    print(Path(__file__).parent)
    print(Path(__file__).parent.parent)

When I run it from the directory that contains it, PathLib thinks that the file's grandparent is the same as its parent.

❯ python test.py

    . # <-- same
    . # <-- directories

But when I run it from the top level, PathLib behaves correctly.

❯ cd ../..
❯ python foo/bar/test.py

    foo/bar # <-- different
    foo     # <-- directories

Am I misunderstanding something about PathLib's API, or is something else causing its output to be sensitive to my working directory?


Solution

  • You need to call Path.resolve() to make your path absolute (a full path including all parent directories and removing all symlinks)

    from pathlib import Path
    print(Path(__file__).resolve().parent)
    print(Path(__file__).resolve().parent.parent)
    

    This will cause the results to include the entire path to each directory, but the behaviour will work wherever it is called from