通常我会推荐使用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("https://stackoverflow.com/a/b/c/d/e/f/g/h")
test("https://stackoverflow.com/a/b/c/d/e/f/g/h/")
test("https://stackoverflow.com/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-19 00:50:15
dsh
我不认为这不会是我想要的东西。 os.path.split将包含在2元素数组中的文件夹从它所在的目录中分离出来。相反,我需要根据斜杠数分割路径并返回单个字符串。 [:7]在这里甚至没有意义。 – imagineerThat 2013-03-19 01:45:52
更新了我的问题。这有点误导。 – imagineerThat 2013-03-19 01:51:12
好点。我应该更加关注我所链接的文档。我相应地更新了我的答案。 – dsh 2013-03-19 02:49:19