URLhttps://learnscript.net/zh-hant/python/file-system/paths/
    複製連結移至說明  範例

    os.path,pathlib 模組,純路徑類別,具體路徑類別介紹

    閱讀 6:08·字數 1843·發佈 
    Youtube 頻道
    訂閱 375

    os.path,pathlib 模組

    對於檔案系統中的路徑,Python 提供了os.pathpathlib模組來處理他們,其中os.path模組包含大量與路徑相關的函式,而pathlib模組則包含與路徑相關的類別。os.path模組與pathlib模組所實作的效果基本一致,但也存在一些差異。

    pathlib模組中的類別,被劃分為純路徑類別和具體路徑類別,我們會對他們逐一介紹。

    pathlib 模組中的純路徑類別

    pathlib模組中的純路徑類別不提供需要真實存取檔案系統的功能,比如,如果一個純路徑物件包含相對路徑,那麽你無法通過該物件將相對路徑轉換為絕對路徑。

    pathlib模組包含三個純路徑類別,分別是PurePathPurePosixPathPureWindowsPath,其中,PurePosixPathPureWindowsPathPurePath的衍生類別,當你嘗試建立一個PurePath物件時,將根據目前的作業系統產生PurePosixPath(UNIX/Linux/macOS)或PureWindowsPath(Windows)類別的執行個體。

    PurePath(*pathsegments)

    pathsegments 參數

    可變參數pathsegments所包含的位置參數是表示路徑的 Python 字串,或實作了抽象基底類別os.PathLike的物件,他們將被用於組成新的路徑。在新路徑被組合的過程中,表示目前目錄的.(不包括表示上一級目錄的..),以及任何能夠被消除的/(不包括新路徑開頭的雙斜線//)將被消除,比如路徑././a/會變為a

    如果一個位置參數表示絕對路徑,那麽該絕對路徑將使之前的位置參數無效,比如,'/a','D:/b'(Windows)將得到路徑D:/b'/etc/a','/usr/b'(UNIX/Linux/macOS)將得到路徑/usr/b

    如果可變參數pathsegments被忽略,或所有位置參數組合之後等於一個空字串,那麽將得到表示目前目錄的路徑.

    當然,你可以直接建立pathlib模組的PurePosixPathPureWindowsPath類別的執行個體,無論目前的作業系統是什麽。

    PurePosixPath(*pathsegments)
    PureWindowsPath(*pathsegments)

    pathsegments 參數

    可變參數pathsegmentsPurePath建構子中的可變參數pathsegments類似,但存在以下不同。

    對於pathlib模組的PureWindowsPath物件,路徑中的\(反斜線)會被轉換為/(斜線),如果一個位置參數表示不帶盤符的根目錄,那麽該位置參數之前的位置參數將無效,除了盤符部分,比如,'C:\\a','\\b'(Windows)將得到路徑C:/b

    # 在 Windows 系統中
    from pathlib import PurePath, PurePosixPath, PureWindowsPath
    # . 和一些 / 被消除,.. 被保留
    PurePath('./a', '..', 'b/.', 'c/')
    PureWindowsPath('a/../b/c')
    # a 失效,盤符 C 被保留,\ 被轉換為 /
    PurePath(r'C:\a', r'\b')
    PureWindowsPath('C:/b')
    # a 失效,\ 被轉換為 /
    PureWindowsPath('a', r'D:\b', 'c')
    PureWindowsPath('D:/b/c')
    # /etc 失效
    PurePosixPath('/etc', '/usr', 'a')
    PurePosixPath('/usr/a')

    pathlib 模組中的具體路徑類別

    與純路徑類別不同,pathlib模組中的具體路徑類別提供了需要真實存取檔案系統的功能,比如,如果一個真實路徑物件包含相對路徑,那麽你可以通過該物件將相對路徑轉換為絕對路徑。

    pathlib模組包含三個純路徑類別,分別是PathPosixPathWindowsPath,其中,PathPurePath的衍生類別,PosixPathPathPurePosixPath的衍生類別,WindowsPathPathPureWindowsPath的衍生類別,當你嘗試建立一個Path物件時,將根據目前的作業系統產生PosixPath(UNIX/Linux/macOS)或WindowsPath(Windows)類別的執行個體。

    Path(*pathsegments)
    PosixPath(*pathsegments)
    WindowsPath(*pathsegments)

    無法在不支援的作業系統中建立 PosixPath 或 WindowsPath 物件

    在 Windows 系統中,你無法建立pathlib模組的PosixPath物件,這將導致例外狀況pathlib._abc.UnsupportedOperation: cannot instantiate 'PosixPath' on your system(Python 3.13 之前的版本將引發例外狀況NotImplementedError),因為該物件僅用於表示 UNIX/Linux/macOS 系統中的路徑。

    在 UNIX/Linux/macOS 系統中,你無法建立pathlib模組的WindowsPath物件,這將導致例外狀況pathlib._abc.UnsupportedOperation: cannot instantiate 'WindowsPath' on your system(Python 3.13 之前的版本將引發例外狀況NotImplementedError),因為該物件僅用於表示 Windows 系統中的路徑。

    # 在 Windows 系統中
    from pathlib import PosixPath
    # ERROR 不支援在 Windows 中建立 PosixPath 物件
    PosixPath()

    pathlib._abc.UnsupportedOperation: cannot instantiate 'PosixPath' on your system