Is there a pathlib method for finding the complement of one path in another?

91 views Asked by At

Given two Python Pathlib paths in which one is a suffix of the other (of unknown depth),

x = Path("/a/b/c/d/e.ext")
y = Path("d/e.ext")

is there a "nice" way to find the complement of y in x? I.e. find:

z = Path("/a/b/c")

I'm thinking of perhaps a sort of inverse to the relative_to() method, but wasn't able to find something suitable in the docs or other SO questions. Currently, I can do either of the following, but they are not very readable:

z = Path(*x.parts[:-len(y.parts)])
z = Path(str(x)[:-len(str(y))])

Thanks!

1

There are 1 answers

0
Dinko Pehar On

You can convert both paths to str and remove subpath to retrieve complement:

>>> from pathlib import Path
>>> x = Path("/a/b/c/d/e.ext")
>>> y = Path("d/e.ext")

>>> Path(str(x).replace(str(y), ""))
PosixPath('/a/b/c')

If subpath is not in path, it will leave path as it is.