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.
os. path. abspath() can be used to get the parent directory. This method is used to get the normalized version of the path.
relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory. Note: This method only computes the relative path. The existence of the given path or directory is not checked.
The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.
parts : returns a tuple that provides access to the path's components. name : the path component without any directory. parent : sequence providing access to the logical ancestors of the path. stem : final path component without its suffix.
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'
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With