0

我想通过正斜杠解析路径(不是文件名)。下面采用完整路径“文件名”并读取到第 7 个“/”。

编辑:当我陈述文件名时,我意识到上述内容令人困惑。我的意思是,我需要解析完整路径。例如,我可能需要左边的前 7 个“/”并删除 5 个尾随的“/”。

Python:

"/".join(filename.split("/")[:7])

重击:

some command that prints filename | cut -d'/' -f1-7`

使用切割工具看起来更干净。有没有更好/更有效的方法来用 Python 编写这个?

4

1 回答 1

5

通常我会推荐使用os.path模块中的函数来处理路径。我更喜欢让库处理有效路径可能发生的所有边缘情况。

正如您在评论中指出的那样,os.path.split()仅拆分最后一个路径元素。要使用它,可以写:

l = []
while True:
    head, tail = os.path.split(filename)
    l.insert(0, tail)
    if head == "/":
        l.insert(0, "")
        break
    filename = head
"/".join(l[:7])

虽然更冗长,但这将正确地规范化重复斜线等伪影。

另一方面,您的使用string.split()匹配cut(1).


示例测试用例:

$ echo '/a/b/c/d/e/f/g/h' | cut -d'/' -f1-7 
/a/b/c/d/e/f

$ echo '/a/b/c/d/e/f/g/h/' | cut -d'/' -f1-7 
/a/b/c/d/e/f

$ echo '/a//b///c/d/e/f/g/h' | cut -d'/' -f1-7
/a//b///c

# Tests and comparison to string.split()

import os.path

def cut_path(filename):
    l = []
    while True:
        head, tail = os.path.split(filename)
        l.insert(0, tail)
        if head == "/":
            l.insert(0, "")
            break
        filename = head
    return "/".join(l[:7])

def cut_string(filename):
    return "/".join( filename.split("/")[:7] )

def test(filename):
    print("input:", filename)
    print("string.split:", cut_string(filename))
    print("os.path.split:", cut_path(filename))
    print()

test("/a/b/c/d/e/f/g/h")
test("/a/b/c/d/e/f/g/h/")
test("/a//b///c/d/e/f/g/h")

# input: /a/b/c/d/e/f/g/h
# string.split: /a/b/c/d/e/f
# os.path.split: /a/b/c/d/e/f
#
# input: /a/b/c/d/e/f/g/h/
# string.split: /a/b/c/d/e/f
# os.path.split: /a/b/c/d/e/f
#
# input: /a//b///c/d/e/f/g/h
# string.split: /a//b///c
# os.path.split: /a/b/c/d/e/f
于 2013-03-19T00:50:15.100 回答