簡體   English   中英

如何使用pathlib獲取Python中兩個絕對路徑之間的相對路徑?

[英]How to get the relative path between two absolute paths in Python using pathlib?

在 Python 3 中,我使用pathlib定義了兩條路徑,例如:

from pathlib import Path

origin = Path('middle-earth/gondor/minas-tirith/castle').resolve()
destination = Path('middle-earth/gondor/osgiliath/tower').resolve()

如何獲得從origindestination的相對路徑? 在這個例子中,我想要一個 function 返回../../osgiliath/tower或類似的東西。

理想情況下,我會有一個始終滿足的 function relative_path

origin.joinpath(
    relative_path(origin, destination)
).resolve() == destination.resolve()

(嗯,理想情況下會有一個運算符-這樣destination == origin / (destination - origin)總是正確的)

請注意,在這種情況下Path.relative_to是不夠的,因為origin不是destination的父級。 另外,我沒有使用符號鏈接,因此可以安全地假設沒有符號鏈接,如果這可以簡化問題。

如何實現relative_path

這很簡單os.path.relpath

import os.path
from pathlib import Path

origin      = Path('middle-earth/gondor/minas-tirith/castle').resolve()
destination = Path('middle-earth/gondor/osgiliath/tower').resolve()

assert os.path.relpath(destination, start=origin) == '..\\..\\osgiliath\\tower'

如果您希望自己的 Python function 將絕對路徑轉換為相對路徑:

def absolute_file_path_to_relative(start_file_path, destination_file_path):
    return (start_file_path.count("/") + start_file_path.count("\\") + 1) * (".." + ((start_file_path.find("/") > -1) and "/" or "\\")) + destination_file_path

這假設:

1) start_file_path從與destination_file_path相同的根文件夾開始。

2) 斜線的類型不能互換。

3)您沒有使用允許文件名中包含斜杠的文件系統。

這些假設可能是優點或缺點,具體取決於您的用例。

缺點:如果您使用的是 pathlib,您將通過混入此 function 來破壞代碼中該模塊的 API 流; 有限的用例; 對於您正在使用的文件系統,輸入必須是無菌的。

優點:運行速度比@AdamSmith 的答案快 202 倍(在 Windows 7 32 位上測試)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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