1

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

Angie
  • 183
  • 3
  • 13

1 Answers1

1

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/
Oleksii Tambovtsev
  • 2,666
  • 1
  • 3
  • 21