os.path --- 常見的路徑名操作

原始碼: Lib/posixpath.py (用於 POSIX 系統) 和 Lib/ntpath.py (用於 Windows).


該模組實現了一些有用的路徑名操作函式。若要讀取或寫入檔案,請參閱 open() 函數,要存取檔案系統,請參閱 os 模組。路徑參數可以以字串、位元組或任何依照 os.PathLike 協議實作的物件傳遞。

與 Unix shell 不同,Python 不會自動進行路徑展開(path expansions)。當應用程式需要進行類似 shell 的路徑展開時,可以明確地呼叫 expanduser()expandvars() 等函式。(另請參閱 glob 模組。)

也參考

pathlib 模組提供了高階的路徑物件。

備註

所有這些函數都只接受位元組或字串物件作為參數。如果回傳的是路徑或檔案名稱,結果將是相同型別的物件。

備註

由於不同的作業系統具有不同的路徑命名慣例,在標準函式庫中的路徑模組有數個版本可供使用,而 os.path 模組都會是運行 Python 之作業系統所適用本地路徑。然而,如果你想要操作始終以某個不同於本機格式表示的路徑,你也可以引入並使用對應的模組。它們都具有相同的介面:

  • posixpath 用於 UNIX 形式的路徑

  • ntpath 用於 Windows 的路徑

在 3.8 版的變更: 對於包含有作業系統層級無法表示之字元或位元組的路徑,exists()lexists()isdir()isfile()islink()ismount() 函式現在會回傳 False,而不是引發例外。

os.path.abspath(path)

回傳經正規化的絕對路徑名 path 。在大多數平台上,這等效於按照以下方式呼叫 normpath() 函式:normpath(join(os.getcwd(), path))

在 3.6 版的變更: 接受一個 path-like object

os.path.basename(path)

回傳路徑名 path 的基底名稱。這是將 path 傳遞給函式 split() 後回傳結果中的第二個元素。請注意,此函式的結果與 Unix 的 basename 程式不同;對於 '/foo/bar/'basename 回傳 'bar',而 basename() 函式回傳空字串('')。

在 3.6 版的變更: 接受一個 path-like object

os.path.commonpath(paths)

回傳序列 paths 中每個路徑名的最長共同子路徑。如果 paths 同時包含絕對路徑和相對路徑、paths 位於不同的磁碟機或 paths 為空,則引發 ValueError。與 commonprefix() 不同,此函式回傳的是有效路徑。

適用:Unix、Windows。

在 3.5 版新加入.

在 3.6 版的變更: 接受一個類路徑物件的序列。

os.path.commonprefix(list)

回傳 list 中所有路徑的最長路徑前綴(逐字元比較)。如果 list 為空,則回傳空字串('')。

備註

由於此函式是逐字元比較,因此可能會回傳無效的路徑。若要獲得有效的路徑,請參考 commonpath() 函式。

>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

>>> os.path.commonpath(['/usr/lib', '/usr/local/lib'])
'/usr'

在 3.6 版的變更: 接受一個 path-like object

os.path.dirname(path)

回傳路徑名 path 的目錄名稱。這是將 path 傳遞給函式 split() 後回傳之成對結果中的第一個元素。

在 3.6 版的變更: 接受一個 path-like object

os.path.exists(path)

如果 path 是一個存在的路徑或一個開啟的檔案描述器則回傳 True。對於已損壞的符號連結則回傳 False。在某些平台上,即使 path 實際存在,如果未被授予執行 os.stat() 的權限,此函式仍可能回傳 False

在 3.3 版的變更: 現在 path 可以是一個整數:如果它是一個開啟的檔案描述器,則回傳 True;否則回傳 False

在 3.6 版的變更: 接受一個 path-like object

os.path.lexists(path)

如果 path 是一個存在的路徑則回傳 True。對於已損壞的符號連結也回傳 True。在缺乏 os.lstat() 的平台上,與 exists() 函式等效。

在 3.6 版的變更: 接受一個 path-like object

os.path.expanduser(path)

在 Unix 和 Windows 上,將引數中以 ~~user 開頭的部分替換為該 user 的家目錄。

在 Unix 上,如果環境變數 HOME 有被設置,則將初始的 ~ 替換為該變數的值;否則將使用內建模組 pwd 在密碼目錄中查找當前使用者的家目錄。對於初始的 ~user,直接在密碼目錄中查找該使用者的家目錄。

在 Windows 上,如果 USERPROFILE 有被設置,則使用該變數的值;否則將結合 HOMEPATHHOMEDRIVE。對於初始的 ~user,會檢查當前使用者的家目錄的最後一個目錄元件是否與 USERNAME 相符,如果相符則替換它。

如果展開失敗或路徑不以波浪符號(tilde)開頭,則回傳原始路徑,不做任何變更。

在 3.6 版的變更: 接受一個 path-like object

在 3.8 版的變更: 在 Windows 上不再使用 HOME 變數。

os.path.expandvars(path)

Return the argument with environment variables expanded. Substrings of the form $name or ${name} are replaced by the value of environment variable name. Malformed variable names and references to non-existing variables are left unchanged.

On Windows, %name% expansions are supported in addition to $name and ${name}.

在 3.6 版的變更: 接受一個 path-like object

os.path.getatime(path)

Return the time of last access of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.

os.path.getmtime(path)

Return the time of last modification of path. The return value is a floating point number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.

在 3.6 版的變更: 接受一個 path-like object

os.path.getctime(path)

Return the system's ctime which, on some systems (like Unix) is the time of the last metadata change, and, on others (like Windows), is the creation time for path. The return value is a number giving the number of seconds since the epoch (see the time module). Raise OSError if the file does not exist or is inaccessible.

在 3.6 版的變更: 接受一個 path-like object

os.path.getsize(path)

Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.

在 3.6 版的變更: 接受一個 path-like object

os.path.isabs(path)

Return True if path is an absolute pathname. On Unix, that means it begins with a slash, on Windows that it begins with a (back)slash after chopping off a potential drive letter.

在 3.6 版的變更: 接受一個 path-like object

os.path.isfile(path)

Return True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.

在 3.6 版的變更: 接受一個 path-like object

os.path.isdir(path)

Return True if path is an existing directory. This follows symbolic links, so both islink() and isdir() can be true for the same path.

在 3.6 版的變更: 接受一個 path-like object

Return True if path refers to an existing directory entry that is a symbolic link. Always False if symbolic links are not supported by the Python runtime.

在 3.6 版的變更: 接受一個 path-like object

os.path.ismount(path)

Return True if pathname path is a mount point: a point in a file system where a different file system has been mounted. On POSIX, the function checks whether path's parent, path/.., is on a different device than path, or whether path/.. and path point to the same i-node on the same device --- this should detect mount points for all Unix and POSIX variants. It is not able to reliably detect bind mounts on the same filesystem. On Windows, a drive letter root and a share UNC are always mount points, and for any other path GetVolumePathName is called to see if it is different from the input path.

在 3.4 版新加入: Support for detecting non-root mount points on Windows.

在 3.6 版的變更: 接受一個 path-like object

os.path.join(path, *paths)

Join one or more path segments intelligently. The return value is the concatenation of path and all members of *paths, with exactly one directory separator following each non-empty part, except the last. That is, the result will only end in a separator if the last part is either empty or ends in a separator. If a segment is an absolute path (which on Windows requires both a drive and a root), then all previous segments are ignored and joining continues from the absolute path segment.

On Windows, the drive is not reset when a rooted path segment (e.g., r'\foo') is encountered. If a segment is on a different drive or is an absolute path, all previous segments are ignored and the drive is reset. Note that since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

在 3.6 版的變更: Accepts a path-like object for path and paths.

os.path.normcase(path)

Normalize the case of a pathname. On Windows, convert all characters in the pathname to lowercase, and also convert forward slashes to backward slashes. On other operating systems, return the path unchanged.

在 3.6 版的變更: 接受一個 path-like object

os.path.normpath(path)

Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes. To normalize case, use normcase().

備註

On POSIX systems, in accordance with IEEE Std 1003.1 2013 Edition; 4.13 Pathname Resolution, if a pathname begins with exactly two slashes, the first component following the leading characters may be interpreted in an implementation-defined manner, although more than two leading characters shall be treated as a single character.

在 3.6 版的變更: 接受一個 path-like object

os.path.realpath(path, *, strict=False)

Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).

If a path doesn't exist or a symlink loop is encountered, and strict is True, OSError is raised. If strict is False, the path is resolved as far as possible and any remainder is appended without checking whether it exists.

備註

This function emulates the operating system's procedure for making a path canonical, which differs slightly between Windows and UNIX with respect to how links and subsequent path components interact.

Operating system APIs make paths canonical as needed, so it's not normally necessary to call this function.

在 3.6 版的變更: 接受一個 path-like object

在 3.8 版的變更: Symbolic links and junctions are now resolved on Windows.

在 3.10 版的變更: 新增 strict 參數。

os.path.relpath(path, start=os.curdir)

Return a relative filepath to path either from the current directory or from an optional start directory. This is a path computation: the filesystem is not accessed to confirm the existence or nature of path or start. On Windows, ValueError is raised when path and start are on different drives.

start defaults to os.curdir.

適用:Unix、Windows。

在 3.6 版的變更: 接受一個 path-like object

os.path.samefile(path1, path2)

Return True if both pathname arguments refer to the same file or directory. This is determined by the device number and i-node number and raises an exception if an os.stat() call on either pathname fails.

適用:Unix、Windows。

在 3.2 版的變更: 新增對 Windows 的支援。

在 3.4 版的變更: Windows now uses the same implementation as all other platforms.

在 3.6 版的變更: 接受一個 path-like object

os.path.sameopenfile(fp1, fp2)

Return True if the file descriptors fp1 and fp2 refer to the same file.

適用:Unix、Windows。

在 3.2 版的變更: 新增對 Windows 的支援。

在 3.6 版的變更: 接受一個 path-like object

os.path.samestat(stat1, stat2)

Return True if the stat tuples stat1 and stat2 refer to the same file. These structures may have been returned by os.fstat(), os.lstat(), or os.stat(). This function implements the underlying comparison used by samefile() and sameopenfile().

適用:Unix、Windows。

在 3.4 版的變更: 新增對 Windows 的支援。

在 3.6 版的變更: 接受一個 path-like object

os.path.split(path)

Split the pathname path into a pair, (head, tail) where tail is the last pathname component and head is everything leading up to that. The tail part will never contain a slash; if path ends in a slash, tail will be empty. If there is no slash in path, head will be empty. If path is empty, both head and tail are empty. Trailing slashes are stripped from head unless it is the root (one or more slashes only). In all cases, join(head, tail) returns a path to the same location as path (but the strings may differ). Also see the functions dirname() and basename().

在 3.6 版的變更: 接受一個 path-like object

os.path.splitdrive(path)

Split the pathname path into a pair (drive, tail) where drive is either a mount point or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.

On Windows, splits a pathname into drive/UNC sharepoint and relative path.

If the path contains a drive letter, drive will contain everything up to and including the colon:

>>> splitdrive("c:/dir")
("c:", "/dir")

If the path contains a UNC path, drive will contain the host name and share, up to but not including the fourth separator:

>>> splitdrive("//host/computer/dir")
("//host/computer", "/dir")

在 3.6 版的變更: 接受一個 path-like object

os.path.splitext(path)

Split the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins with a period and contains at most one period.

If the path contains no extension, ext will be '':

>>> splitext('bar')
('bar', '')

If the path contains an extension, then ext will be set to this extension, including the leading period. Note that previous periods will be ignored:

>>> splitext('foo.bar.exe')
('foo.bar', '.exe')
>>> splitext('/foo/bar.exe')
('/foo/bar', '.exe')

Leading periods of the last component of the path are considered to be part of the root:

>>> splitext('.cshrc')
('.cshrc', '')
>>> splitext('/foo/....jpg')
('/foo/....jpg', '')

在 3.6 版的變更: 接受一個 path-like object

os.path.supports_unicode_filenames

True if arbitrary Unicode strings can be used as file names (within limitations imposed by the file system).