问题描述
我想找到两个绝对路径之间的相对路径。我现有的代码通常使用 pathlib.Path
与文件系统交互,但我遇到了一个问题,用 os.path.relpath
似乎很容易解决,但(到目前为止)用 pathlib.Path
难以解决.
我有:
- (A),目录的绝对路径,
/home/project/cluster-scope/base/namespaces/acm
- (B),from (A) 到另一个目录的相对路径,
../../../components/monitoring-rbac
- (C),第二个目录的绝对路径,
/home/project/cluster-scope/base/core/namespaces/acm
我想从 (C) 计算到 (B) 的新相对路径。这有效:
>>> import os
>>> path_A = '/home/project/cluster-scope/base/namespaces/acm'
>>> path_B = '../../../components/monitoring-rbac'
>>> path_C = '/home/project/cluster-scope/base/core/namespaces/acm'
>>> path_B_abs = os.path.abspath(os.path.join(path_A,path_B))
>>> os.path.relpath(path_B_abs,path_C)
'../../../../components/monitoring-rbac'
但这不会:
>>> from pathlib import Path
>>> path_A = Path('/home/project/cluster-scope/base/namespaces/acm')
>>> path_B = Path('../../../components/monitoring-rbac')
>>> path_C = Path('/home/project/cluster-scope/base/core/namespaces/acm')
>>> path_B_abs = (path_A / path_B).resolve()
>>> path_B_abs.relative_to(path_C)
Traceback (most recent call last):
File "<stdin>",line 1,in <module>
File "/usr/lib64/python3.9/pathlib.py",line 928,in relative_to
raise ValueError("{!r} is not in the subpath of {!r}"
ValueError: '/home/project/cluster-scope/components/monitoring-rbac' is not in the subpath of '/home/project/cluster-scope/base/core/namespaces/acm' OR one path is relative and the other is absolute.
该 ValueError
异常中的消息似乎不准确,或位于
最少误导:这两条路径显然共享一个共同的父级。是
有什么方法可以使用
pathlib.Path
?我意识到我可以只使用 os.path.relpath
并完成它,但我很好奇我是否误解了 pathlib
的 relative_to
方法的使用。
解决方法
显然这是不可能的。根据{{3}}:
我同意改进错误消息(可能还有文档)是值得的。
从来没有明确过 relative_to 只会看起来更深(永远不会生成前导“..”部分) - 文档中最接近的提示是 os.path.relpath 是不同的(甚至不在relative_to() 部分)。
在当前版本中,an issue 说
"""Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path),raise ValueError.
"""