我有一个字符串变量,它代表一个dos路径,例如:

var = “d:\stuff\morestuff\Furtherdown\THEFILE.txt”

我想把这个字符串分成:

[ “d”, “stuff”, “morestuff”, “Furtherdown”, “THEFILE.txt” ]

我尝试过使用split()和replace(),但它们要么只处理第一个反斜杠,要么将十六进制数字插入字符串。

我需要以某种方式将这个字符串变量转换为原始字符串,以便我可以解析它。

最好的方法是什么?

我还应该添加,var的内容,即我试图解析的路径,实际上是一个命令行查询的返回值。这不是我自己生成的路径数据。它存储在一个文件中,命令行工具不会转义反斜杠。


当前回答

from os import path as os_path

然后

def split_path_iter(string, lst):
    head, tail = os_path.split(string)
    if head == '':
        return [string] + lst
    else:
        return split_path_iter(head, [tail] + lst)

def split_path(string):
    return split_path_iter(string, [])

或者,受以上答案启发(更优雅):

def split_path(string):
    head, tail = os_path.split(string)
    if head == '':
        return [string]
    else:
        return split_path(head) + [tail]

其他回答

这对我来说很管用:

>>> a=r"d:\stuff\morestuff\furtherdown\THEFILE.txt"
>>> a.split("\\")
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']

当然,您可能还需要从第一个组件中剥离冒号,但保留它可以重新组装路径。

r修饰符将字符串字面量标记为“raw”;注意嵌入的反斜杠是如何不加倍的。

使用ntpath.split ()

下面的代码行可以处理:

C:/路径/路径 C://path//path C:\路径\路径 C:\路径\路径

Path = re.split(r'[///\]', Path)

功能性的方法,用发电机。

def split(path):
    (drive, head) = os.path.splitdrive(path)
    while (head != os.sep):
        (head, tail) = os.path.split(head)
        yield tail

在行动:

>>> print([x for x in split(os.path.normpath('/path/to/filename'))])
['filename', 'to', 'path']

调整了@Mike Robins在开始时避免空路径元素的解决方案:

def parts(path):
    p,f = os.path.split(os.path.normpath(path))
    return parts(p) + [f] if f and p else [p] if p else []

Os.path.normpath()实际上只需要一次,并且可以在递归的单独入口函数中完成。