通常我會推薦使用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