with pathlib.Path.relative_to
we can get relative paths with:
JavaScript
x
4
1
>>> from pathlib import Path
2
>>> Path("/path/to/foo/bar/thing").relative_to("/path/to/foo")
3
PosixPath('bar/thing')
4
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
JavaScript
1
3
1
p = Path("/path/to/foo/bar/thing")
2
relative_to = 'foo'
3
do
JavaScript
1
2
1
relative_p = Path(*p.parts[p.parts.index(relative_to) + 1:])
2
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
JavaScript
1
3
1
import os
2
relative_p = Path(str(p).split(f'{os.sep}{relative_to}{os.sep}', maxsplit=1)[-1])
3