我有一个字符串变量,它代表一个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”;注意嵌入的反斜杠是如何不加倍的。

我会这么做

import os
path = os.path.normpath(path)
path.split(os.sep)

首先,将路径字符串规范化为适合操作系统的字符串。那么操作系统。Sep在字符串函数split中用作分隔符必须是安全的。

关于关于mypath.split("\\")的内容最好表示为mypath.split(os.sep)。sep是你的特定平台的路径分隔符(例如,\ for Windows, / for Unix,等等),Python构建知道使用哪个。如果您使用sep,那么您的代码将是平台不可知的。

你可以简单地使用最python化的方法(IMHO):

import os

your_path = r"d:\stuff\morestuff\furtherdown\THEFILE.txt"
path_list = your_path.split(os.sep)
print path_list

这将给你:

['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']

这里的线索是使用操作系统。Sep而不是“\\”或“/”,因为这使得它与系统无关。

要从驱动器号中删除冒号(尽管我看不出你为什么要这样做),你可以这样写:

path_list[0] = path_list[0][0]

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

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']