11.2. os.path — 常见路径名操纵

此模块实现一些有用路径名函数。要读取/写入文件见 open() ,和访问文件系统见 os 模块。path 参数可以按字符串或 bytes 形式传递。鼓励应用程序将文件名表示成 Unicode 字符串。很遗憾,有些文件名在 Unix 可能无法以字符串表示,所以,需要在 Unix 支持任意文件名的应用程序应使用 bytes 对象表示路径名。反之亦然,使用 bytes 对象无法表示所有 Windows 文件名(按标准 mbcs 编码),因此,Windows 应用程序应使用字符串对象访问所有文件。

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

另请参阅

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

注意

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

注意

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

  • posixpath 用于 UNIX 样式路径
  • ntpath 用于 Windows 路径
  • macpath 用于旧样式 MacOS 路径
os.path. abspath ( path )

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

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() 函数返回空字符串 ( '' ).

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 ( '' ). Note that this may return invalid paths because it works a character at a time.

os.path. dirname ( path )

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

os.path. exists ( path )

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

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

os.path. lexists ( path )

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

os.path. expanduser ( path )

在 Unix 和 Windows,返回自变量采用初始分量的 ~ or ~user 替换 user ‘s home directory.

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

在 Windows, HOME and USERPROFILE will be used if set, otherwise a combination of HOMEPATH and HOMEDRIVE will be used. An initial ~user is handled by stripping the last directory component from the created user path derived above.

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

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} .

os.path. getatime ( path )

Return the time of last access of path . The return value is a number giving the number of seconds since the epoch (see the time 模块)。引发 OSError 若文件不存在 (或不可访问)。

os.stat_float_times() 返回 True ,结果是浮点数。

os.path. getmtime ( path )

Return the time of last modification of path . The return value is a number giving the number of seconds since the epoch (see the time 模块)。引发 OSError 若文件不存在 (或不可访问)。

os.stat_float_times() 返回 True ,结果是浮点数。

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

os.path. getsize ( path )

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

os.path. isabs ( path )

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

os.path. isfile ( path )

返回 True if path is an existing regular file. This follows symbolic links, so both islink() and isfile() 可以为 True 对于相同路径。

os.path. isdir ( path )

返回 True if path is an existing directory. This follows symbolic links, so both islink() and isdir() 可以为 True 对于相同路径。

返回 True if path refers to a directory entry that is a symbolic link. Always False if symbolic links are not supported by the python runtime.

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. 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.

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 ( os.sep ) 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 .

os.path. normcase ( path )

Normalize the case of a pathname. On Unix and Mac OS X, this returns the path unchanged; on case-insensitive filesystems, it converts the path to lowercase. On Windows, it also converts forward slashes to backward slashes. Raise a TypeError if the type of path 不是 str or bytes .

os.path. normpath ( path )

通过折叠多余分隔符和上层引用以规范化路径名,以便 A//B , A/B/ , A/./B and A/foo/../B 全部变为 A/B 。此字符串操纵可能改变包含符号链接的路径含义。在 Windows,它将正斜杠转换为反斜杠。要规范化大小写,使用 normcase() .

os.path. realpath ( path )

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

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

返回相对文件路径为 path 从当前目录或从可选 start 目录。这种路径计算:不用访问文件系统就能确认存在 (或性质) 为 path or start .

start 默认为 os.curdir .

可用性:Unix Windows。

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

os.path. sameopenfile ( fp1 , fp2 )

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

可用性:Unix Windows。

3.2 版改变: 添加 Windows 支持。

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 支持。

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() .

os.path. splitdrive ( path )

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

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

若 path 包含驱动器号,驱动器将包含直到并包括冒号的一切。如 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. e.g. splitdrive("//host/computer/dir") 返回 ("//host/computer", "/dir")

os.path. splitext ( path )

分割路径名 path 成一对 (root, ext) 这样 root + ext == path ,和 ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') 返回 ('.cshrc', '') .

os.path. splitunc ( path )

从 3.3 版起弃用: 使用 splitdrive 代替。

分割路径名 path 成一对 (unc, rest) so that unc is the UNC mount point (such as r'\\host\mount' ), if present, and rest the rest of the path (such as r'\path\file.ext' ). For paths containing drive letters, unc will always be the empty string.

可用性:Windows。

os.path. supports_unicode_filenames

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

上一话题

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

下一话题

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

本页