Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's pathlib get parent's relative path

Tags:

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.

like image 784
Mojimi Avatar asked Jan 28 '19 12:01

Mojimi


People also ask

How do I find parent directory in Python?

os. path. abspath() can be used to get the parent directory. This method is used to get the normalized version of the path.

How do you find the relative path in Python?

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.

What does Pathlib path () do?

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.

What does Pathlib path return?

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.


2 Answers

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'
like image 189
Martijn Pieters Avatar answered Sep 22 '22 22:09

Martijn Pieters


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))
like image 37
Benoît P Avatar answered Sep 20 '22 22:09

Benoît P