pathlib.Path.relative_与vs.os.Path.relpath

2024-05-18 00:49:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我想找出两条绝对路径之间的相对路径。我的现有代码通常使用pathlib.Path与文件系统交互,但我遇到了一个问题,这个问题似乎很容易用os.path.relpath解决,但(到目前为止)难以用pathlib.Path解决

我有:

  • (A) ,指向目录的绝对路径,/home/project/cluster-scope/base/namespaces/acm
  • (B) ,从(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并完成它,但我很好奇我是否误解了pathlibrelative_to方法的使用


Tags: pathcoreprojecthomebaseoscomponentsmonitoring
1条回答
网友
1楼 · 发布于 2024-05-18 00:49:31

显然这是不可能的。根据an issue

I agree it's worth improving the error message (and probably the docs too).

It's never made clear that relative_to only looks deeper (won't ever generate leading ".." parts) - the closest hint in the docs is that os.path.relpath is different (and that isn't even in the relative_to() section).

在当前版本中docstring表示

"""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.
"""

相关问题 更多 >