我希望通过正斜杠解析路径(而不是文件名)。下面是完整的路径“文件名”,并读取到第7 "/“。
编辑:当我声明文件名时,我意识到上面的内容很混乱。我是说,我需要解析完整的路径。例如,我可能需要左边的前7 "/"s,然后去掉5尾/“s.”
Python:
"/".join(filename.split("/")[:7])巴什:
some command that prints filename | cut -d'/' -f1-7`用切割工具看上去干净多了。是否有更好/更有效的方法来用Python编写这篇文章?
发布于 2013-03-19 00:50:15
通常,我建议使用来自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/fhttps://stackoverflow.com/questions/15489550
复制相似问题