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

此模块实现一些有用路径名函数。要读取/写入文件见 open() ,和访问文件系统见 os 模块。

注意

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

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

注意

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

  • posixpath 用于 UNIX 样式路径
  • ntpath 用于 Windows 路径
  • macpath 用于旧样式 MacOS 路径
  • os2emxpath for OS/2 EMX paths
os.path. abspath ( path )

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

1.5.2 版新增。

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 物理存在。

os.path. lexists ( path )

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

2.4 版新增。

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

1.5.2 版新增。

Changed in version 2.3: 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 模块)。引发 os.error 若文件不存在 (或不可访问)。

1.5.2 版新增。

Changed in version 2.3: 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 模块)。引发 os.error 若文件不存在 (或不可访问)。

2.3 版新增。

os.path. getsize ( path )

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

1.5.2 版新增。

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

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.

os.path. normpath ( path )

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

os.path. realpath ( path )

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

2.2 版新增。

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

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

start 默认为 os.curdir .

Availability: Windows, Unix.

2.6 版新增。

os.path. samefile ( path1 , path2 )

返回 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 a os.stat() call on either pathname fails.

可用性:Unix。

os.path. sameopenfile ( fp1 , fp2 )

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

可用性:Unix。

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。

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 is either a drive specification or the empty string. On systems which do not use drive specifications, drive 始终是空字符串。在所有情况下, drive + tail 将如同 path .

New in version 1.3.

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', '') .

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

os.path. splitunc ( path )

分割路径名 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. walk ( path , visit , arg )

Calls the function visit 采用自变量 (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 名称 lists the files in the directory (gotten from os.listdir(dirname) )。 visit function may modify 名称 to influence the set of directories visited below dirname , e.g. to avoid visiting certain parts of the tree. (The object referred to by 名称 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

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

2.3 版新增。

上一话题

10. 文件和目录访问

下一话题

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

本页