Trying to remove the last part of a path python

Viewed 170

I have a path which is A/B/C/D. I am trying to remove the last part so that I end up with A/B/C/. I've done:

path = pathlib.Path(r"A/B/C/D")
path.parent

which gives me

PosixPath('A/B/C')

However, it has removed the forward slash after "C". Is there a similar way to do this so that it does not remove the last forward slash? Thanks

1 Answers

os.path.join(path, '') will add the trailing slash if it's not there:

import pathlib
import os

path = pathlib.Path(r"A/B/C/D")
print(path.parent)
print(os.path.join(path.parent, ''))

Output:

A/B/C
A/B/C/
Related