首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:在Python中剪切等效?

Python:在Python中剪切等效?
EN

Stack Overflow用户
提问于 2013-03-19 00:39:04
回答 1查看 2.2K关注 0票数 0

我希望通过正斜杠解析路径(而不是文件名)。下面是完整的路径“文件名”,并读取到第7 "/“。

编辑:当我声明文件名时,我意识到上面的内容很混乱。我是说,我需要解析完整的路径。例如,我可能需要左边的前7 "/"s,然后去掉5尾/“s.

Python:

代码语言:javascript
复制
"/".join(filename.split("/")[:7])

巴什:

代码语言:javascript
复制
some command that prints filename | cut -d'/' -f1-7`

用切割工具看上去干净多了。是否有更好/更有效的方法来用Python编写这篇文章?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-19 00:50:15

通常,我建议使用来自os.path模块的函数来处理路径。我更喜欢让库处理所有可用有效路径发生的边缘情况。

正如您在注释中指出的那样,os.path.split()只拆分了最后一个路径元素。要使用它,人们可以写:

代码语言:javascript
复制
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)的语义相匹配。

样本测试用例:

代码语言:javascript
复制
$ 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

代码语言:javascript
复制
# 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/f
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15489550

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档