Python: Python中如何实现cut的功能?

0 投票
1 回答
2462 浏览
提问于 2025-04-17 19:35

我想要通过斜杠来解析一个路径(不是文件名)。下面的代码是针对完整路径“文件名”的,它会读取到第7个“/”。

补充说明:我意识到之前提到文件名可能让人困惑。我其实是想解析完整路径。比如,我可能需要获取前7个“/”的部分,并去掉后面多余的5个“/”。

Python:

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

Bash:

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

使用cut工具看起来整洁多了。在Python中有没有更好或更高效的写法呢?

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

撰写回答