2013-03-19 123 views
0

我想用正斜槓解析路徑(不是文件名)。下面採用完整路徑「文件名」並讀取到第7個「/」。Python:在Python中相當於什麼?

編輯:我意識到上述情況令人困惑,當我說文件名。我的意思是,我需要解析完整的路徑。例如我可能需要在左邊的前7個「/」和刪除5個尾隨的「/」。

的Python:

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

擊:

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

它看起來與切割工具,以便更清潔。有沒有更好/更有效的方式來編寫Python?

回答

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("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 
+0

我不認爲這不會是我想要的東西。 os.path.split將包含在2元素數組中的文件夾從它所在的目錄中分離出來。相反,我需要根據斜槓數分割路徑並返回單個字符串。 [:7]在這裏甚至沒有意義。 – imagineerThat 2013-03-19 01:45:52

+0

更新了我的問題。這有點誤導。 – imagineerThat 2013-03-19 01:51:12

+0

好點。我應該更加關注我所鏈接的文檔。我相應地更新了我的答案。 – dsh 2013-03-19 02:49:19