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

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

我想把这个字符串分成:

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

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

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

最好的方法是什么?

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


当前回答

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

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

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]

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

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

对于这个问题,我实际上无法给出一个真正的答案(因为我来这里是希望自己找到一个答案),但对我来说,不同方法的数量和所有提到的注意事项都是Python操作系统最可靠的指标。Path模块非常需要这个内置函数。

使用ntpath.split ()