Python's pathlib get parent's relative path

Mojimi picture Mojimi · Jan 28, 2019 · Viewed 11.1k times · Source

Consider the following Path:

import pathlib
path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')

How can I extract the exact string documents\importantdocuments from that Path?

I know this example looks silly, the real context here is translating a local file to a remote download link.

Answer

Martijn Pieters picture Martijn Pieters · Jan 28, 2019

Use the PurePath.relative_to() method to produce a relative path.

You weren't very clear as to how the base path is determined; here are two options:

secondparent = path.parent.parent
homedir = pathlib.Path(r'C:\users\user1')

then just use str() on the path.relative_to(secondparent) or path.relative_to(homedir) result.

Demo:

>>> import pathlib
>>> path = pathlib.Path(r'C:\users\user1\documents\importantdocuments')
>>> secondparent = path.parent.parent
>>> homedir = pathlib.Path(r'C:\users\user1')
>>> str(path.relative_to(secondparent))
'documents\\importantdocuments'
>>> str(path.relative_to(homedir))
'documents\\importantdocuments'