44

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.

Salvatore
  • 10,815
  • 4
  • 31
  • 69
Mojimi
  • 2,561
  • 9
  • 52
  • 116

2 Answers2

80

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
-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))
Benoît P
  • 3,179
  • 13
  • 31