簡體   English   中英

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)

給定AB是否有一種干凈、准確的方法來計算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.Pathparents字段:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM