Python's pathlib get parent's relative path
30,233
Solution 1
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'
Solution 2
This works on any OS and every version of Python:
import os
os.path.join(os.path.basename(os.path.dirname(p)),os.path.basename(p))
This works on python 3:
str(p.relative_to(p.parent.parent))
Author by
Mojimi
Updated on July 22, 2022Comments
-
Mojimi almost 2 years
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 thatPath
?I know this example looks silly, the real context here is translating a local file to a remote download link.
-
Martijn Pieters over 5 yearsSo you want it relative to the second parent directory? Or a hardcoded path?
-
Mojimi over 5 years@MartijnPieters I want the string
documents\importantdocuments
-
Martijn Pieters over 5 yearsI know that. But why that section of your path? Is it because those are the last two parts of the path? Or do you have
Path(r'C:\users\user1')
somewhere else and that's the reference path? -
Mojimi over 5 years@MartijnPieters because I need the parent folder relative path
-
-
Ankirama almost 4 yearsHe's using pathlib, he didn't asked for an alternative.