Skip to content
Advertisement

How to get relative path given a parent of unknown location with Python’s pathlib?

with pathlib.Path.relative_to we can get relative paths with:

JavaScript

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

do

JavaScript

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
Advertisement