以防万一我错过了什么,然后才能为问题实施自己的解决方案。
在我们的构建系统中,我总是需要使用相对路径来保持所有项目的可移动性。因此,构建脚本应生成文件的相对路径。
然而,似乎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实现不起作用?