代码之家  ›  专栏  ›  技术社区  ›  Anders

关于python中路径的问题

  •  1
  • Anders  · 技术社区  · 15 年前

    假设我的目录路径如下所示:

    this/is/the/basedir/path/a/include
    this/is/the/basedir/path/b/include
    this/is/the/basedir/path/a
    this/is/the/basedir/path/b
    

    在python中,如何将这些路径拆分,使它们看起来像这样:

    a/include
    b/include
    a
    b
    

    如果我运行os.path.split(path)[1]它将显示:

    include
    include
    a
    b
    

    我应该在这里尝试什么,我应该查看一些regex命令,或者在没有它的情况下可以这样做吗?事先谢谢。

    编辑全部:我用正则表达式解决了它,他妈的方便工具:)

    4 回复  |  直到 15 年前
        1
  •  3
  •   unwind    15 年前

    可能是这样的,取决于前缀的硬编码方式:

    def removePrefix(path, prefix):
        plist = path.split(os.sep)
        pflist = prefix.split(os.sep)
        rest = plist[len(pflist):]
        return os.path.join(*rest)
    

    用途:

    print removePrefix("this/is/the/basedir/path/b/include", "this/is/the/basedir/path")
    b/include
    

    假设您在一个目录分隔符所在的平台上( os.sep )实际上是正斜杠)。

    这段代码试图将路径作为比字符串更高级的东西来处理。不过,这并不是最佳选择,你可以(或者应该)做更多的清洁和规范化来提高安全性。

        2
  •  1
  •   mp.    15 年前

    可能是这样的:

    result = []
    
    prefix = os.path.commonprefix(list_of_paths)
    for path in list_of_paths:
        result.append(os.path.relpath(path, prefix))
    

    这仅在2.6中有效。2.5和2.5之前版本中的relapath仅在路径是当前工作目录的情况下才起作用。

        3
  •  1
  •   sunqiang    15 年前

    怎么样 partition ?
    它在sep的第一次出现时拆分字符串,并返回包含分隔符前部分、分隔符本身和分隔符后部分的3元组。如果找不到分隔符,则返回一个包含字符串本身的3元组,后跟两个空字符串。

    data = """this/is/the/basedir/path/a/include
    this/is/the/basedir/path/b/include
    this/is/the/basedir/path/a
    this/is/the/basedir/path/b"""
    for line in data.splitlines():
        print line.partition("this/is/the/basedir/path/")[2]
    
    #output
    a/include
    b/include
    a
    b
    

    作者对新评论进行了更新:
    根据目录是否以“include”结尾而不是:

    import os.path
    data = """this/is/the/basedir/path/a/include
    this/is/the/basedir/path/b/include
    this/is/the/basedir/path/a
    this/is/the/basedir/path/b"""
    for line in data.splitlines():
        if line.endswith('include'):
            print '/'.join(line.rsplit("/",2)[-2:])
        else:
            print os.path.split(line)[1]
            #or just
            # print line.rsplit("/",1)[-1]
    #output
    a/include
    b/include
    a
    b
    
        4
  •  0
  •   Alex Martelli    15 年前

    虽然标准不是100%清楚,但从操作人员的评论中可以看出,关键问题是路径的最后一个组件是否以“include”结尾。如果是这样,为了避免最后一个组件出现错误,例如“dontinclude”(另一个答案是尝试字符串匹配而不是路径匹配),我建议:

    def lastpart(apath):
        pieces = os.path.split(apath)
        final = -1
        if pieces[-1] == 'include':
            final = -2
        return '/'.join(pieces[final:])