bukzor
bukzor

Reputation: 38532

pathlib get base path, given the absolute and relative paths

I have:

I want:

We have well defined, reliable functions for two of the three relationships between these paths:

Is there a clean, exact way to compute C given A and B? Or: What's the third, missing operation? Or must I resort to string manipulation?

Upvotes: 1

Views: 570

Answers (2)

Alexander Pivovarov
Alexander Pivovarov

Reputation: 4990

You can use parents field of pathlib.Path:

C = (A.parents[len(B.parents)-1]
       if 1 <= len(B.parents) <= len(A.parents) else None)
if C is None or A != C.joinpath(B):
    # B is not a suffix of A, proceed accordingly

Upvotes: 0

azro
azro

Reputation: 54168

What about path as string manipulation using str.removesuffix (since py3.9)

A = Path('/a/b/.../m/n/.../z.txt')
B = Path('n/.../z.txt')
C = Path(A.as_posix().removesuffix(B.as_posix()))
print(C)  # /a/b/.../m

Or remove part from the end of A until A == C/B

C = Path(A.as_posix())
while C != Path("/") and not B == A.relative_to(C):
    C = C.parent

Upvotes: 2

Related Questions