I want to split a string on the second last slash,
so if I have a string like /tmp/fold/merge/annots I want to get /tmp/fold/ and merge/annots returned.
Same if I have /tmp/long/dir/fold/merge/annots I want to get /tmp/long/dir/fold/ and merge/annots
What’s the best way to do this? I’ve tried rsplit and split a few times but not getting what I want
>Solution :
String splitting works, but I would actually use pathlib for this.
import pathlib
p = pathlib.Path('/tmp/long/dir/fold/merge/annots')
p.parts[-2:]
# ('merge', 'annots')
If you need it as a path object,
result = pathlib.Path(*p.parts[-2:])
which can be converted directly to string if you need to use it that way specifically.