with pathlib.Path.relative_to
we can get relative paths with:
>>> from pathlib import Path >>> Path("/path/to/foo/bar/thing").relative_to("/path/to/foo") PosixPath('bar/thing')
But what if i don’t know the exact path of the parent directory (but i do know its name)?
for example:
Path("/path/to/foo/bar/thing")
relative to"foo"
=>PosixPath('bar/thing')
Path("/path/to/foo/bar/thing")
relative to"to"
=>PosixPath('foo/bar/thing')
Path("/another_path/to/foo/bar/thing")
relative to"foo"
=>PosixPath('bar/thing')
how do i get a relative path relative to an arbitrary parent directory like this?
Advertisement
Answer
Given
p = Path("/path/to/foo/bar/thing") relative_to = 'foo'
do
relative_p = Path(*p.parts[p.parts.index(relative_to) + 1:])
Essentially, we grab the parts of the path, find the index of relative_to
and slice those parts using that index. Then we pass the sliced parts back to the Path()
constructor to get back our relative path.
Another option
import os relative_p = Path(str(p).split(f'{os.sep}{relative_to}{os.sep}', maxsplit=1)[-1])