我有一个字符串变量,它代表一个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]

其他回答

使用ntpath.split ()

这里的问题首先要从如何创建字符串开始。

a = "d:\stuff\morestuff\furtherdown\THEFILE.txt"

通过这种方式,Python试图对这些对象进行特殊处理:\s、\m、\f和\T。在您的情况下,\f被视为一个表单提要(0x0C),而其他反斜杠被正确处理。你需要做的是:

b = "d:\\stuff\\morestuff\\furtherdown\\THEFILE.txt"      # doubled backslashes
c = r"d:\stuff\morestuff\furtherdown\THEFILE.txt"         # raw string, no doubling necessary

一旦你把它们分开,你就会得到你想要的结果。

我会这么做

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

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

非常简单的方法:

var.replace ('\\', '/'). split(“/”)

真可惜!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/