简体   繁体   English

在Python中获取最后一个'/'或'\\\\'字符

[英]Get the last '/' or '\\' character in Python

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? 我如何获得“./A/B/”部分? The direction of the slashes can be the same 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. 基本上,我想要一个没有文件部分的文件的路径。

通常使用os.path.dirname()来实现此目的。

I believe you are looking for os.path.split . 我相信你正在寻找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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM