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.
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'