10.1. os.path — 常见路径操作

This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module.

注解

On Windows, many of these functions do not properly support UNC pathnames. splitunc() and ismount() do handle them correctly.

与unix shell不同,Python不执行任何 自动 路径扩展。当应用程序需要类似shell的路径扩展时,可以显式调用诸如 expanduser()expandvars() 之类的函数。 (另请参见 glob 模块。)

注解

由于不同的操作系统具有不同的路径名称约定,因此标准库中有此模块的几个版本。 os.path 模块始终是适合Python运行的操作系统的路径模块,因此可用于本地路径。但是,如果操作的路径 总是 以一种不同的格式显示,那么也可以分别导入和使用各个模块。它们都具有相同的界面:

  • posixpath 用于Unix 样式的路径

  • ntpath 用于 Windows 路径

  • macpath 用于旧 MacOS 样式的路径

  • os2emxpath for OS/2 EMX paths

os.path.abspath(path)

返回路径 path 的绝对路径(标准化的)。在大多数平台上,这等同于用 normpath(join(os.getcwd(), path)) 的方式调用 normpath() 函数。

1.5.2 新版功能.

os.path.basename(path)

返回路径 path 的基本名称。这是将 path 传入函数 split() 之后,返回的一对值中的第二个元素。请注意,此函数的结果与Unix basename 程序不同。basename'/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. If 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)

Return True if path refers to an existing path. Returns False for broken symbolic links. On some platforms, this function may return False if permission is not granted to execute os.stat() on the requested file, even if the path physically exists.

os.path.lexists(path)

如果 path 指向一个已存在的路径,返回 True。对于失效的符号链接,返回 False。在缺失 os.lstat() 的平台上等同于 exists()

2.4 新版功能.

os.path.expanduser(path)

在 Unix 和 Windows 上,将参数中开头部分的 ~~user 替换为当前 用户 的家目录并返回。

在 Unix 上,开头的 ~ 会被环境变量 HOME 代替,如果变量未设置,则通过内置模块 pwd 在 password 目录中查找当前用户的主目录。以 ~user 开头则直接在 password 目录中查找。

在 Windows 上,如果设置了 HOMEUSERPROFILE 则将使用它们,否则将使用 HOMEPATHHOMEDRIVE 的组合。 原本的 ~user 处理方式为从上述方法所生成的用户路径中截去最后一级目录。

如果展开路径失败,或者路径不是以波浪号开头,则路径将保持不变。

os.path.expandvars(path)

输入带有环境变量的路径作为参数,返回展开变量以后的路径。$name${name} 形式的子字符串被环境变量 name 的值替换。格式错误的变量名称和对不存在变量的引用保持不变。

在 Windows 上,除了 $name${name} 外,还可以展开 %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 module). Raise os.error if the file does not exist or is inaccessible.

1.5.2 新版功能.

在 2.3 版更改: If os.stat_float_times() returns True, the result is a floating point number.

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 module). Raise os.error if the file does not exist or is inaccessible.

1.5.2 新版功能.

在 2.3 版更改: If os.stat_float_times() returns True, the result is a floating point number.

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 os.error if the file does not exist or is inaccessible.

2.3 新版功能.

os.path.getsize(path)

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

1.5.2 新版功能.

os.path.isabs(path)

如果 path 是一个绝对路径,则返回 True。在 Unix 上,它就是以斜杠开头,而在 Windows 上,它可以是去掉驱动器号后以斜杠(或反斜杠)开头。

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.

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.

Return 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)

Return True if pathname path is a mount point: a point in a file system where a different file system has been mounted. 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.

os.path.join(path, *paths)

合理地拼接一个或多个路径部分。返回值是 path*paths 所有值的连接,每个非空部分后面都紧跟一个目录分隔符 (os.sep),除了最后一部分。这意味着如果最后一部分为空,则结果将以分隔符结尾。如果参数中某个部分是绝对路径,则绝对路径前的路径都将被丢弃,并从绝对路径部分开始连接。

在 Windows 上,遇到绝对路径部分(例如 r'\foo')时,不会重置盘符。如果某部分路径包含盘符,则会丢弃所有先前的部分,并重置盘符。请注意,由于每个驱动器都有一个“当前目录”,所以 os.path.join("c:", "foo") 表示驱动器 C: 上当前目录的相对路径 (c:foo),而不是 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.

os.path.normpath(path)

通过折叠多余的分隔符和对上级目录的引用来标准化路径名,所以 A//BA/B/A/./BA/foo/../B 都会转换成 A/B。这个字符串操作可能会改变带有符号链接的路径的含义。在 Windows 上,本方法将正斜杠转换为反斜杠。要规范大小写,请使用 normcase()

os.path.realpath(path)

返回指定文件的规范路径,消除路径中存在的任何符号链接(如果操作系统支持)。

2.2 新版功能.

os.path.relpath(path[, start])

返回从当前目录或 start 目录(可选)到达 path 之间要经过的相对路径。这仅仅是对路径的计算,不会访问文件系统来确认 pathstart 的存在性或属性。

开始 默认为 os.curdir

Availability: Windows, Unix.

2.6 新版功能.

os.path.samefile(path1, path2)

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

Availability: Unix.

os.path.sameopenfile(fp1, fp2)

如果文件描述符 fp1fp2 指向相同文件,则返回 True

Availability: Unix.

os.path.samestat(stat1, stat2)

如果 stat 元组 stat1stat2 指向相同文件,则返回 True。这些 stat 元组可能是由 os.fstat()os.lstat()os.stat() 返回的。本函数实现了 samefile()sameopenfile() 底层所使用的比较过程。

Availability: Unix.

os.path.split(path)

将路径 path 拆分为一对,即 (head, tail),其中,tail 是路径的最后一部分,而 head 里是除最后部分外的所有内容。tail 部分不会包含斜杠,如果 path 以斜杠结尾,则 tail 将为空。如果 path 中没有斜杠,head 将为空。如果 path 为空,则 headtail 均为空。head 末尾的斜杠会被去掉,除非它是根目录(即它仅包含一个或多个斜杠)。在所有情况下,join(head, tail) 指向的位置都与 path 相同(但字符串可能不同)。另请参见函数 dirname()basename()

os.path.splitdrive(path)

Split the pathname path into a pair (drive, tail) where drive is either a drive specification 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.

1.3 新版功能.

os.path.splitext(path)

将路径 path 拆分为一对,即 (root, ext),使 root + ext == path,其中 ext 为空或以英文句点开头,且最多包含一个句点。路径前的句点将被忽略,例如 splitext('.cshrc') 返回 ('.cshrc', '')

在 2.6 版更改: Earlier versions could produce an empty root when the only period was the first character.

os.path.splitunc(path)

Split the pathname path into a pair (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.

Availability: Windows.

os.path.walk(path, visit, arg)

Calls the function visit with arguments (arg, dirname, names) for each directory in the directory tree rooted at path (including path itself, if it is a directory). The argument dirname specifies the visited directory, the argument names lists the files in the directory (gotten from os.listdir(dirname)). The visit function may modify names to influence the set of directories visited below dirname, e.g. to avoid visiting certain parts of the tree. (The object referred to by names must be modified in place, using del or slice assignment.)

注解

Symbolic links to directories are not treated as subdirectories, and that walk() therefore will not visit them. To visit linked directories you must identify them with os.path.islink(file) and os.path.isdir(file), and invoke walk() as necessary.

注解

This function is deprecated and has been removed in Python 3 in favor of os.walk().

os.path.supports_unicode_filenames

如果(在文件系统限制下)允许将任意 Unicode 字符串用作文件名,则为 True

2.3 新版功能.