[英]How to get the relative path between two absolute paths in Python using pathlib?
[英]pathlib get base path, given the absolute and relative paths
我有:
A = Path('/a/b/.../m/n/.../z.txt')
B = Path('n/.../z.txt')
我想:
C = Path('/a/b/.../m')
我們為這些路徑之間的三種關系中的兩種關系定義了明確的、可靠的函數:
B == A.relative_to(C)
A == C / B
C == A.unknown_operator(B)
給定A
和B
是否有一種干凈、准確的方法來計算C
? 或者:第三個缺失的操作是什么? 還是我必須求助於字符串操作?
使用str.removesuffix
作為字符串操作的路徑怎么樣(從 py3.9 開始)
A = Path('/a/b/.../m/n/.../z.txt')
B = Path('n/.../z.txt')
C = Path(A.as_posix().removesuffix(B.as_posix()))
print(C) # /a/b/.../m
或從A
的末尾刪除部分,直到A == C/B
C = Path(A.as_posix())
while C != Path("/") and not B == A.relative_to(C):
C = C.parent
您可以使用pathlib.Path
的parents
字段:
C = (A.parents[len(B.parents)-1]
if 1 <= len(B.parents) <= len(A.parents) else None)
if C is None or A != C.joinpath(B):
# B is not a suffix of A, proceed accordingly
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.