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!
You can convert both paths to
str
and remove subpath to retrieve complement:If subpath is not in path, it will leave path as it is.