Skip to content
Advertisement

python Pathlib, how do I remove leading directories to get relative paths?

Let’s say I have this directory structure.

JavaScript

I want to isolate path components relative to root1/root2, i.e. strip out the leading root part, giving relative directories:

JavaScript

The root depth can be arbitrary and the files, the node of this tree, can also reside at different levels.

This code does it, but I am looking for Pathlib’s pythonic way to do it.

JavaScript

Advertisement

Answer

TLDR: use Path.relative_to:

JavaScript

Full example:

JavaScript

Prints

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement