6

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?

MatrixManAtYrService
  • 8,023
  • 1
  • 50
  • 61

1 Answers1

9

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

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50
  • Does not work for network shared directories (e.g. "\\my_network_space\some_dir"). Any ideas? – nlhnt Jul 11 '22 at 06:57