2

以防万一我错过了什么,在我为问题实施自己的解决方案之前。

在我们的构建系统中,我总是必须使用相对路径来保持所有项目的可移动性。因此,构建脚本应该生成文件的相对路径。

然而,python 库中似乎没有可以处理父路径步骤的函数,如下例所示:

from pathlib import Path
dir_a = Path("/home/example/solution/project")
file_b = Path("/home/example/solution/config.h")

我想获得file_b相对于的路径dir_a。因此,如果我从 开始dir_a,相对路径将指向file_b

最好的结果是:

>>> file_b.relative_to(dir_a)
Path("../config.h")

举这个稍微复杂一点的例子:

from pathlib import Path
dir_a = Path("/home/example/solution/project_a")
file_b = Path("/home/example/solution/project_b/config.h")

最好的结果是:

>>> file_b.relative_to(dir_a)
Path("../project_b/config.h")

使用这些方法的两个示例.relative_to都不起作用并引发异常:

ValueError: '/home/example/solution/project_b/config.h' does not start with '/home/example/solution/project_a'

os.path.relpath方法按预期工作,但返回一个字符串而不是一个Path对象:

>>> os.path.relpath(file_b, dir_a)
'../project_b/config.h'

所以我想知道我是否在这里遗漏了什么......

如何使用 Path 对象获取与父目录的相对路径?

为什么对象的relative_to实现Path不起作用?

4

1 回答 1

-2

一些路径 x 需要在一些基本路径内。您遇到了ValueError异常,因为 project_b 与 project_a 无关,而是与解决方案文件夹相关。

例如,为了更好地理解,您应该:

base = Path("/home/example/solution")
b_file = Path("/home/example/solution/project_b/config.h")
b_file.relative_to(base) # output >>> WindowsPath('project_b/config.h')

编辑:您可以使用或 获取当前文件夹中包含Path对象的相对目录。Path.glob()Path.iterdir()

你会发现哪一个更适合你的情况。

基本上,你可以做的是:

base = Path('/home/example/solution') 
g = base.glob('/*') # grabs all files and dirs relative to the current folder as Path objects
try:
    while g:
        i = next(g)
        if i.match('project_b'):
            # if here is my folder then work with it
            b_file = i.joinpath('config.h')
        else:
            # work on a better look up maybe
            pass
except StopIteration:
    pass
于 2018-09-17T20:16:46.673 回答