I have a string that has the path of the file stored in it.
path = \home\linux\testfile\abc\work
now I want to write a function with which I can remove all the characters occurring after the last '\\'
.
So,
new_path = \home\linux\testfile\abc
Is there a way I can do it? Slicing doesn't help because the number of characters after the last '\' isn't fixed. I know i need to post an attempt but i don't even understand how do i start this.
CodePudding user response:
You can use rsplit
to start from the right and only split one time.
>>> path = '\home\linux\testfile\abc\work'
>>> path.rsplit('\\', 1)
['\\home\\linux\\testfile\\abc', 'work']
>>> path.rsplit('\\', 1)[0]
'\\home\\linux\\testfile\\abc'
CodePudding user response:
You can try with os
library.
>>> os.path.split(r"\home\linux\testfile\abc\work")
('\\home\\linux\\testfile\\abc', 'work')
CodePudding user response:
Does it mean that I get the parent directory
>>> a="/home/pro"
>>> os.path.dirname(a)
'/home'
CodePudding user response:
You can use head, tail = os.path.split(path)
Check here