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

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

我想把这个字符串分成:

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

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

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

最好的方法是什么?

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


当前回答

递归是为了好玩。

这不是最优雅的回答,但应该适用于任何地方:

import os

def split_path(path):
    head = os.path.dirname(path)
    tail = os.path.basename(path)
    if head == os.path.dirname(head):
        return [tail]
    return split_path(head) + [tail]

其他回答

让我们假设你有一个文件filedata.txt的内容:

d:\stuff\morestuff\furtherdown\THEFILE.txt
d:\otherstuff\something\otherfile.txt

您可以读取和分割文件路径:

>>> for i in open("filedata.txt").readlines():
...     print i.strip().split("\\")
... 
['d:', 'stuff', 'morestuff', 'furtherdown', 'THEFILE.txt']
['d:', 'otherstuff', 'something', 'otherfile.txt']

你可以简单地使用最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(p):
    a,b = os.path.split(p)
    return (split_path(a) if len(a) and len(b) else []) + [b]

调整了@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()实际上只需要一次,并且可以在递归的单独入口函数中完成。

真可惜!python os。Path没有os。Path。splitall这样的东西

不管怎样,这是对我有用的,来源:https://www.oreilly.com/library/view/python-cookbook/0596001673/ch04s16.html

import os

a = '/media//max/Data/'

def splitall(path):
    # https://www.oreilly.com/library/view/python-cookbook/0596001673/ch04s16.html
    allparts = []
    while 1:
        parts = os.path.split(path)
        if parts[0] == path:  # sentinel for absolute paths
            allparts.insert(0, parts[0])
            break
        elif parts[1] == path: # sentinel for relative paths
            allparts.insert(0, parts[1])
            break
        else:
            path = parts[0]
            allparts.insert(0, parts[1])
    return allparts

x = splitall(a)
print(x)

z = os.path.join(*x)
print(z)

输出:

['/', 'media', 'max', 'Data', '']
/media/max/Data/