开发者

Get the last '/' or '\\' character in Python

开发者 https://www.devze.com 2022-12-22 13:12 出处:网络
If I have a string that looks like either ./A/B/c.d OR .\\A\\B\\c.d How do I get just the \"./A/B/\" part? The direction of the slashes can be the same开发者_StackOverflow as they are passed.

If I have a string that looks like either

./A/B/c.d

OR

.\A\B\c.d

How do I get just the "./A/B/" part? The direction of the slashes can be the same开发者_StackOverflow as they are passed.

This problem kinda boils down to: How do I get the last of a specific character in a string?

Basically, I want the path of a file without the file part of it.


Normally os.path.dirname() is used for this.


I believe you are looking for os.path.split. It splits the path into head and tail... tail being the file, head being the path up to the file.


>>> p="./A/B/c.d"
>>> import os
>>> os.path.split(p)
('./A/B', 'c.d')
>>> os.path.split(p)[0]
'./A/B'
>>> os.path.dirname(p)
'./A/B'
>>> p.rsplit("/",1)[0]
'./A/B
0

精彩评论

暂无评论...
验证码 换一张
取 消