如何通过名称获取路径的特定父级?

How to get a specific parent of a path by its name?

我有一个函数,returns 特定 父项的完整路径,我通过常量名称查找。我目前正在使用 os.path 和字符串作为路径,所以现在这是用正则表达式完成的。

我想要的是例如常量parent = d能够得到:

/a/b/c/d/e      -->  /a/b/c/d
/a/b/c/d/e/f    -->  /a/b/c/d
/root/a/b/c/d/e -->  /root/a/b/c/d

注意:如示例所示,我不想依赖双方的任何固定位置。

我尝试了两种方法,但都感觉有点笨拙:

  1. 使用parts in order to find the correct parents元素:

    >>> path = "/a/b/c/d/e/f"
    >>> parts = Path(path).parts
    >>> parent_index = len(parts) - 1 - parts.index('d') - 1
    >>> Path(path).parents[parent_index]
    PosixPath('/a/b/c/d')
    
  2. 使用parts并连接相关的:

    >>> path = "/root/a/b/c/d/e"
    >>> parts = Path(path).parts
    >>> Path(*parts[:parts.index('d')+1])
    PosixPath('/root/a/b/c/d')
    

我会说第二个似乎是合理的,但我的问题仍然是:是否有更直接的 pythonic 方法来实现这一点? parents 的重复索引和切片感觉效率低下且相当混乱。


P.S。如果该部分不存在于路径中,则足以引发异常或任何指示器(现在我用 index 将代码包装在上面 try/except)。

您可以使用 while 循环来继续向后搜索给定名称的父代:

path = Path("/a/b/c/d/e/f")
while path.name != 'd':
    path = path.parent
    assert path.name, 'No parent found with the given name'
print(path)

这输出:

/a/b/c/d

您可以拆分和连接您的字符串并使用项目的索引 +1

path='/a/b/c/d/e/f'
lpath=path.split('/')
index=lpath.index('d')+1
'/'.join(lpath[0:index])

输出:

'/a/b/c/d'