簡體   English   中英

如何獲取 pathlib.Path 對象的絕對路徑?

[英]How to get absolute path of a pathlib.Path object?

使用pathlib模塊創建路徑對象,例如:

p = pathlib.Path('file.txt')

p對象將指向文件系統中的某個文件,因為我可以做例如p.read_text()

如何獲取字符串中p對象的絕對路徑?

似乎我可以使用例如os.path.abspath(p)來獲取絕對路徑,但是使用os.path方法很尷尬,因為我認為pathlib應該是os.path的替代品。

使用resolve()

只需像這樣使用Path.resolve()

p = p.resolve()

這使您的路徑成為絕對路徑,並將所有相對部分替換為絕對部分,並將所有符號鏈接替換為物理路徑。 在不區分大小寫的文件系統上,它還將規范化大小寫( file.TXT變為file.txt )。

在 Python 3.11 之前避免使用absolute()

替代方法absolute()在 Python 3.11 之前沒有記錄或測試(請參閱@Jim Fasarakis Hilliard 創建的錯誤報告中的討論)。

修復程序於 2022 年 1 月合並。

區別

resolveabsolute之間的區別在於absolute()不會替換路徑的符號鏈接(符號鏈接)部分,並且它永遠不會引發FileNotFoundError 它也沒有修改案例。

如果你想避免resolve() (例如你想保留符號鏈接、大小寫或相關部分),那么在 Python <3.11 上使用它:

p = Path.cwd() / "file.txt"

即使您提供的路徑是絕對路徑,這也有效——在這種情況下, cwd (當前工作目錄)將被忽略。

注意 Windows 上不存在的文件

如果文件不存在,則在 Windows 上的 Python 3.6 到 3.9 中, resolve()不會在當前工作目錄前添加。 請參閱問題 38671 ,已在 Python 3.10 中修復。

當心 FileNotFoundError

在 v3.6 之前的 Python 版本中,如果磁盤上不存在路徑, resolve()引發FileNotFoundError

因此,如果有任何風險,請事先使用p.exists()檢查或嘗試/捕獲錯誤。

# check beforehand
if p.exists():
    p = p.resolve()

# or except afterward
try:
    p = p.resolve()
except FileNotFoundError:
    # deal with the missing file here
    pass

如果您正在處理不在磁盤上的路徑,並且您不在 Python 3.6+ 上,最好恢復到os.path.abspath(str(p))

從 3.6 開始, resolve()僅在使用strict參數時引發FileNotFoundError

# might raise FileNotFoundError
p = p.resolve(strict=True)

但請注意,使用strict會使您的代碼與 3.6 之前的 Python 版本不兼容,因為這些版本不接受strict參數。

如果我的理解正確,您正在尋找方法.absolute ,其文檔指出:

>>> print(p.absolute.__doc__)
Return an absolute version of this path.  This function works
        even if the path doesn't point to anything.

        No normalization is done, i.e. all '.' and '..' will be kept along.
        Use resolve() to get the canonical path to a file.

使用我系統上的測試文件返回:

>>> p = pathlib.Path('testfile')
>>> p.absolute()
PosixPath('/home/jim/testfile')

這種方法似乎是 PathPath繼承對象的一種新的、仍然沒有記錄的補充。

創建了一個問題來記錄這一點

如果您只是想要路徑並且不想檢查文件是否存在,您可以這樣做

str(p)

作為操作部分中的文檔。

pathlib.Path.cwd() / p

這是CPython 核心開發人員推薦的“一種顯而易見的方式”。

p.resolve()至少不會為 Windows 上不存在的文件返回絕對路徑。

p.absolute()沒有記錄。

暫無
暫無

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

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