56

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.

0

2 Answers 2

100

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'
Sign up to request clarification or add additional context in comments.

1 Comment

is there a way to keep the "starting dot" , e.g. "./my-relative-dir" with relative_to()
-3

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))

1 Comment

He's using pathlib, he didn't asked for an alternative.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.