python 父路径,python - 使用父目录步骤创建相对路径 - SO中文参考 - www.soinside.com...

以防万一我错过了什么,然后才能为问题实施自己的解决方案。

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

然而,似乎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实现不起作用?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值