Reputation: 38532
I have:
A = Path('/a/b/.../m/n/.../z.txt')
B = Path('n/.../z.txt')
I want:
C = Path('/a/b/.../m')
We have well defined, reliable functions for two of the three relationships between these paths:
B == A.relative_to(C)
A == C / B
C == A.unknown_operator(B)
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
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
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