os.path — 常见路径名操纵

源代码: Lib/posixpath.py (对于 POSIX) 和 Lib/ntpath.py (对于 Windows)。


此模块实现一些有用路径名函数。要读取/写入文件见 open() ,和访问文件系统见 os 模块。可以传递的路径参数如字符串、字节或任何对象有实现 os.PathLike 协议。

不像 Unix Shell,Python 不做任何 automatic 路径扩展。函数譬如 expanduser() and expandvars() 可以被明确援引,当应用程序期望像 Shell 的路径扩展时。(另请参阅 glob 模块。)

另请参阅

pathlib 模块提供高级路径对象。

注意

这些函数全部只接受字节 (或字符串) 对象作为它们的参数。结果是相同类型的对象,如果返回路径 (或文件名)。

注意

由于不同操作系统有不同的路径名约定,因此,此模块在标准库中有几个版本。 os.path 模块是始终适合在操作系统运行 Python 的路径模块,因此可用于本地路径。不管怎样,还可以导入和使用单独模块,若想要操纵的路径 always 是某种不同格式。它们都有相同接口:

  • posixpath 用于 UNIX 样式路径

  • ntpath 用于 Windows 路径

3.8 版改变: exists() , lexists() , isdir() , isfile() , islink() ,和 ismount() 现在返回 False 而不是引发异常对于包含 OS 级别不可表示的字符 (或字节) 的路径。

os.path. abspath ( path )

返回规范化绝对版本的路径名 path 。在大多数平台,这相当于调用函数 normpath() 如下: normpath(join(os.getcwd(), path)) .

3.6 版改变: 接受 像路径对象 .

os.path. basename ( path )

返回基名称为路径名 path 。这是返回对的第 2 元素通过传递 path 到函数 split() . Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' 返回 'bar' basename() 函数返回空字符串 ( '' ).

3.6 版改变: 接受 像路径对象 .

os.path. commonpath ( paths )

返回每路径名的最长公共子路径为序列 paths 。引发 ValueError if paths 包含绝对和相对路径名两者, paths 在不同驱动器中,或者若 paths 为空。不像 commonprefix() ,这返回有效路径。

可用性 :Unix、Windows。

3.5 版新增。

3.6 版改变: 接受序列的 像路径对象 .

os.path. commonprefix ( list )

Return the longest path prefix (taken character-by-character) that is a prefix of all paths in list 。若 list is empty, return the empty string ( '' ).

注意

This function may return invalid paths because it works a character at a time. To obtain a valid path, see commonpath() .

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

3.6 版改变: 接受 像路径对象 .

os.path. dirname ( path )

返回目录名为路径名 path 。这是对的第一元素返回通过传递 path 到函数 split() .

3.6 版改变: 接受 像路径对象 .

os.path. exists ( path )

返回 True if path 引用现有路径 (或打开文件描述符)。返回 False 对于断开的符号链接。在某些平台,此函数可能返回 False 若未授予权限以执行 os.stat() 对请求文件,即使 path 物理存在。

3.3 版改变: path 现在可以是整数: True 被返回若它是打开的文件描述符, False 否则。

3.6 版改变: 接受 像路径对象 .

os.path. lexists ( path )

返回 True if path 引用现有路径。返回 True 对于断开的符号链接。相当于 exists() 当平台缺乏 os.lstat() .

3.6 版改变: 接受 像路径对象 .

os.path. expanduser ( path )

在 Unix 和 Windows,返回自变量采用初始分量的 ~ or ~user 替换 user 的 Home (主) 目录。

在 Unix,初始 ~ 的替换是通过环境变量 HOME 若有设置;否则在 password 目录下查找当前用户的 home 目录通过内置模块 pwd 。初始 ~user 是直接在 password 目录下查找。

在 Windows, USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by checking that the last directory component of the current user’s home directory matches USERNAME , and replacing it if so.

If the expansion fails or if the path does not begin with a tilde, the path is returned unchanged.

3.6 版改变: 接受 像路径对象 .

3.8 版改变: 不再使用 HOME 在 Windows。

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.

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

3.6 版改变: 接受 像路径对象 .

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 模块)。引发 OSError 若文件不存在 (或不可访问)。

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 模块)。引发 OSError 若文件不存在 (或不可访问)。

3.6 版改变: 接受 像路径对象 .

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 模块)。引发 OSError 若文件不存在 (或不可访问)。

3.6 版改变: 接受 像路径对象 .

os.path. getsize ( path )

返回以字节为单位的大小对于 path 。引发 OSError 若文件不存在 (或不可访问)。

3.6 版改变: 接受 像路径对象 .

os.path. isabs ( path )

返回 True if path 是绝对路径名。在 Unix,这意味着它以斜杠开始,在 Windows,它以 (反) 斜杠开始在砍掉潜在驱动器字母后。

3.6 版改变: 接受 像路径对象 .

os.path. isfile ( path )

返回 True if path existing 常规文件。这遵循符号链接,因此 islink() and isfile() 可以为 True 对于相同路径。

3.6 版改变: 接受 像路径对象 .

os.path. isdir ( path )

返回 True if path existing 目录。这遵循符号链接,因此 islink() and isdir() 可以为 True 对于相同路径。

3.6 版改变: 接受 像路径对象 .

返回 True if path 引用 existing 目录条目是符号链接。始终 False 若 Python 运行时不支持符号链接。

3.6 版改变: 接受 像路径对象 .

os.path. ismount ( path )

返回 True 若路径名 path 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 版改变: 接受 像路径对象 .

os.path. join ( path , * paths )

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

On Windows, the drive letter is not reset when an absolute path component (e.g., r'\foo' ) is encountered. If a component contains a drive letter, all previous components are thrown away and the drive letter 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 版改变: 接受 像路径对象 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 版改变: 接受 像路径对象 .

os.path. normpath ( path )

通过折叠多余分隔符和上层引用以规范化路径名,以便 A//B , A/B/ , A/./B and A/foo/../B 全部变为 A/B 。此字符串操纵可能改变包含符号链接的路径含义。在 Windows,它将正斜杠转换为反斜杠。要规范化大小写,使用 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 版改变: 接受 像路径对象 .

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

返回指定文件名的典型路径,消除路径中遇到的任何符号链接 (若操作系统支持它们)。

If a path doesn’t exist or a symlink loop is encountered, and strict is True , OSError 被引发。若 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 版改变: 接受 像路径对象 .

3.8 版改变: 符号链接和结在 Windows 现在能解析。

3.10 版改变: strict 参数被添加。

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

返回相对文件路径为 path 从当前目录或从可选 start 目录。这种路径计算:不用访问文件系统就能确认存在 (或性质) 为 path or start 。在 Windows, ValueError 被引发当 path and start 在不同驱动器中。

start 默认为 os.curdir .

可用性 :Unix、Windows。

3.6 版改变: 接受 像路径对象 .

os.path. samefile ( path1 , path2 )

返回 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 现在使用与所有其它平台相同的实现。

3.6 版改变: 接受 像路径对象 .

os.path. sameopenfile ( fp1 , fp2 )

返回 True 若文件描述符 fp1 and fp2 参考同一文件。

可用性 :Unix、Windows。

3.2 版改变: 添加 Windows 支持。

3.6 版改变: 接受 像路径对象 .

os.path. samestat ( stat1 , stat2 )

返回 True 若状态元组 stat1 and stat2 refer to the same file. These structures may have been returned by os.fstat() , os.lstat() ,或 os.stat() . This function implements the underlying comparison used by samefile() and sameopenfile() .

可用性 :Unix、Windows。

3.4 版改变: 添加 Windows 支持。

3.6 版改变: 接受 像路径对象 .

os.path. split ( path )

分割路径名 path 成一对 (head, tail) where tail 是最后路径名分量而 head 是至此的一切前导。 tail 部分从不包含斜杠;若 path 以斜杠结尾, tail 将为空。若没有斜杠在 path , head 将为空。若 path 为空,两者 head and tail 为空。剥离结尾斜杠从 head 除非它是 root (仅一个或多个斜杠)。在所有情况下, join(head, tail) 返回同一位置路径如 path (但字符串可能不同)。另请参阅函数 dirname() and basename() .

3.6 版改变: 接受 像路径对象 .

os.path. splitdrive ( path )

分割路径名 path 成一对 (drive, tail) where drive 是挂载点 (或空字符串)。在不使用驱动器规范的系统, drive 始终是空字符串。在所有情况下, drive + tail 将如同 path .

在 Windows,将路径名分割成 "驱动器/UNC" 共享点和相对路径。

若路径包含驱动器字母,驱动器将包含冒号 (包括冒号) 之前的一切:

>>> 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 版改变: 接受 像路径对象 .

os.path. splitext ( path )

分割路径名 path 成一对 (root, ext) 这样 root + ext == path ,和扩展名 ext 为空,或以句点开头且最多包含一句点。

若路径不包含扩展名, ext 将是 '' :

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

若路径包含扩展名,则 ext 将被设为此扩展名,包括前导句点。注意,之前句点将被忽略:

>>> 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 版改变: 接受 像路径对象 .

os.path. supports_unicode_filenames

True 若可以将任意 Unicode 字符串用作文件名 (在由文件系统施加的局限性内)。

上一话题

pathlib — 面向对象的文件系统路径

下一话题

fileinput — 遍历来自多个输入流的行

本页