0

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.

I'mahdi
  • 23,382
  • 5
  • 22
  • 30
Pushpesh
  • 9
  • 5

6 Answers6

2

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'
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • This works for me i used to think that split removes after the first occurrence. – Pushpesh Jul 13 '22 at 09:59
  • @Pushpesh, welcome, `split` strat from `left` BUT `rsplit` start from `right` and you can also control how many split – I'mahdi Jul 13 '22 at 10:01
2

Why not simply use pathlib? Path objects never leave trailing path delimiters.

from pathlib import Path

path = Path("\home\linux\testfile\abc\work") 
new_path = path.parent
null
  • 1,944
  • 1
  • 14
  • 24
1

You can try with os library.

>>> import os
>>> data = os.path.split(r"\home\linux\testfile\abc\work")
>>> data[1]
'work'
>>> data[0]
'\\home\\linux\\testfile\\abc'
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
1

Does it mean that I get the parent directory

>>> a="/home/pro"
>>> os.path.dirname(a)
'/home'
Vox
  • 506
  • 2
  • 13
1
path = "\\home\\linux\\testfile\\abc\\work"
pat = path.split("\\")

pat.pop()

path = "\\".join(pat)


print(path)

output

-1

You can use head, tail = os.path.split(path)

Check here

bogdaN
  • 39
  • 3