2013-03-19 57 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