通常我会推荐使用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