1

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.

2
  • please work with os import or related Commented Jul 13, 2022 at 9:47
  • Why does slicing not work? Slice it and get the last element by using sliced_path[-1] on the resulting list. Or use rsplit Commented Jul 13, 2022 at 9:48

6 Answers 6

3

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' 
Sign up to request clarification or add additional context in comments.

2 Comments

This works for me i used to think that split removes after the first occurrence.
@Pushpesh, welcome, split strat from left BUT rsplit start from right and you can also control how many split
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 

Comments

1

Does it mean that I get the parent directory

>>> a="/home/pro" >>> os.path.dirname(a) '/home' 

Comments

1
path = "\\home\\linux\\testfile\\abc\\work" pat = path.split("\\") pat.pop() path = "\\".join(pat) print(path) 

output

1 Comment

How is this a significant improvement over the accepted answer?
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' 

Comments

-1

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

Check here

5 Comments

This only works if the last part of the directory is called "work"...
Yes, i know, i was giving an example, then a reference to what i used, and he can work with it. He can just os.path.split(path) then work with (head,tail) output.
Yes, but OP asked for a function that works generally, not an example...
This approach won't work for me because the last part isn't fixed.
I have edited my answer. you can just take any path into a variable and pass it to split()

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.