簡體   English   中英

如何使用 Pathlib 獲取相對路徑

[英]How to get relative paths with Pathlib

我開始使用from pathlib import Path代替os.path.join()來連接我的路徑。 考慮以下代碼:

from pathlib import Path
import cv2

rootfolder = "rootyrooty"
file = "alittlefile"
image_path = Path(rootfolder, file)
image = cv2.imread(image_path.as_posix())

我正在使用image_path.as_posix()來獲取完整的字符串,因此我可以將image_path傳遞給imread function。 直接輸入image_path不起作用,因為它返回WindowsPath('rootyrooty/alittlefile')但我需要"rootyrooty/alittlefile" (因為imread接受字符串而不是 windowsPath 對象)。 我是否必須使用pathlib中的另一個組件而不是Path ,所以我可以將image_path輸入到imread function 中。 喜歡:

from pathlib import thefunctionyetidontknow
image_path = thefunctionyetidontknow("rootyrooty","alittlefile")
print("image_path")
# returns "rootyrooty/alittlefile"

謝謝。

您可以使用 Python 的內置str function 將Path object 轉換為字符串:

from pathlib import Path
import cv2

rootfolder = "rootyrooty"
file = "alittlefile"
image_path = Path(rootfolder, file)
image = cv2.imread(str(image_path))

您組合路徑的方式非常好。 值得懷疑的是as_posix()在 Windows 機器上的使用。 一些接受字符串作為路徑的庫可以使用 posix 路徑分隔符,但最好使用 os 分隔符。 要使用文件系統分隔符獲取路徑,請使用str

https://docs.python.org/3/library/pathlib.html

路徑的字符串表示是原始文件系統路徑本身(以本機形式,例如在 Windows 下使用反斜杠),您可以將其傳遞給任何 function,將文件路徑作為字符串:

 >> p = PurePath('/etc') >> str(p) '/etc' >> p = PureWindowsPath('c:/Program Files') >> str(p) 'c:\\Program Files'

暫無
暫無

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

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