os.path官方文档(附翻译)

时间:2024-10-16 15:05:44

This module implements some useful functions on pathnames. To read or write files see open(), and for accessing the filesystem see the os module. The path parameters can be passed as either strings, or bytes. Applications are encouraged to represent file names as (Unicode) character strings. Unfortunately, some file names may not be representable as strings on Unix, so applications that need to support arbitrary file names on Unix should use bytes objects to represent path names. Vice versa, using bytes objects cannot represent all file names on Windows (in the standard mbcs encoding), hence Windows applications should use string objects to access all files.

这个模块在路径名上实现了一些有用的函数。要读取或写入文件,请参阅open(),要访问文件系统,请参阅os模块。路径参数可以作为字符串或字节传递。鼓励应用程序将文件名表示为(Unicode)字符串。不幸的是,有些文件名在Unix上可能无法表示为字符串,因此需要支持Unix上任意文件名的应用程序应该使用字节对象来表示路径名。反之,使用字节对象不能表示Windows上的所有文件名(在标准的mbcs编码中),因此Windows应用程序应该使用字符串对象来访问所有文件。

Unlike a unix shell, Python does not do any automatic path expansions. Functions such as expanduser() and expandvars() can be invoked explicitly when an application desires shell-like path expansion. (See also the glob module.)

与unix shell不同,Python不执行任何自动路径扩展。当应用程序需要类shell路径展开时,可以显式地调用expanduser()和expandvars()等函数。(参见glob模块)。

Note All of these functions accept either only bytes or only string objects as their parameters. The result is an object of the same type, if a path or file name is returned.

所有这些函数都只接受字节或字符串对象作为参数。如果返回路径或文件名,则结果是相同类型的对象。

Note Since different operating systems have different path name conventions, there are several versions of this module in the standard library. The os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths. However, you can also import and use the individual modules if you want to manipulate a path that is always in one of the different formats. They all have the same interface:
posixpath for UNIX-style paths
ntpath for Windows paths
macpath for old-style MacOS paths

由于不同的操作系统具有不同的路径名称约定,因此标准库中有几个版本的此模块。操作系统。path模块始终是适合运行Python的操作系统的路径模块,因此可以用于本地路径。不过,如果希望操作始终以不同格式之一显示的路径,还可以导入和使用各个模块。它们都有相同的界面:
用于unix样式路径的posixpath
ntpath用于Windows路径
macpath用于老式MacOS路径

os.path.abspath(path)
Return a normalized absolutized version of the pathname path. On most platforms, this is equivalent to calling the function normpath() as follows: normpath(join(os.getcwd(), path)).
Changed in version 3.6: Accepts a path-like object.

返回路径名路径的规范化绝对版本。在大多数平台上,这相当于按如下方式调用函数normpath(): normpath(join(os.getcwd(), path))。
在3.6版中更改:接受一个类似路径的对象。

os.path.basename(path)
Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').
Changed in version 3.6: Accepts a path-like object.

返回路径名路径的基本名称。这是通过将路径传递给函数split()返回的对的第二个元素。注意,这个函数的结果与Unix basename程序不同;当'/foo/bar/'的basename返回'bar'时,basename()函数返回一个空字符串(")。
在3.6版中更改:接受一个类似路径的对象。

os.path.commonpath(paths)
Return the longest common sub-path of each pathname in the sequence paths. Raise ValueError if paths contains both absolute and relative pathnames, or if paths is empty. Unlike commonprefix(), this returns a valid path.
Availability: Unix, Windows.
New in version 3.5.
Changed in version 3.6: Accepts a sequence of path-like objects.

返回序列路径中每个路径名的最长公共子路径。如果路径同时包含绝对和相对路径名,或者路径为空,则引发ValueError。与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. If list is empty, return the empty string ('').

返回最长路径前缀(逐个字符获取),它是列表中所有路径的前缀。如果list是空的,返回空字符串(")。

Note This function may return invalid paths because it works a character at a time. To obtain a valid path, see commonpath().
此函数可能返回无效路径,因为它一次处理一个字符。要获得有效路径,请参见commonpath()。
>>>
>>> os.path.commonprefix(['/usr/lib', '/usr/local/lib'])
'/usr/l'

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

os.path.dirname(path)
Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().
Changed in version 3.6: Accepts a path-like object.

返回路径名路径的目录名。这是通过将路径传递给函数split()返回的对的第一个元素。
在3.6版中更改:接受一个类似路径的对象。

os.path.exists(path)
Return True if path refers to an existing path or an open file descriptor. 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.
Changed in version 3.3: path can now be an integer: True is returned if it is an open file descriptor, False otherwise.
Changed in version 3.6: Accepts a path-like object.

如果path引用现有路径或打开的文件描述符,则返回True。为断开的符号链接返回False。在某些平台上,如果没有授予对请求的文件执行os.stat()的权限,则该函数可能返回False,即使该路径实际存在。
在3.3版中更改:path现在可以是整数:如果是打开的文件描述符,返回True,否则返回False。
在3.6版中更改:接受一个类似路径的对象。

os.path.lexists(path)
Return True if path refers to an existing path. Returns True for broken symbolic links. Equivalent to exists() on platforms lacking os.lstat().
Changed in version 3.6: Accepts a path-like object.

如果path引用现有路径,则返回True。对于断开的符号链接返回True。在缺少os.lstat()的平台上等效exists()。
在3.6版中更改:接受一个类似路径的对象。

os.path.expanduser(path)
On Unix and Windows, return the argument with an initial component of ~ or ~user replaced by that user’s home directory.
On Unix, an initial ~ is replaced by the environment variable HOME if it is set; otherwise the current user’s home directory is looked up in the password directory through the built-in module pwd. An initial ~user is looked up directly in the password directory.
On 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.
Changed in version 3.6: Accepts a path-like object.

在Unix和Windows上,返回参数,初始组件的~或~user替换为该用户的主目录。
在Unix上,如果设置了初始~,则将其替换为环境变量HOME;否则,通过内置模块pwd在password目录中查找当前用户的主目录。直接在密码目录中查找初始~用户。
在Windows上,如果设置了HOME和USERPROFILE,将使用HOME和USERPROFILE,否则将使用HOMEPATH和HOMEDRIVE的组合。通过从上面派生的创建的用户路径中剥离最后一个目录组件来处理初始~用户。
如果展开失败,或者路径没有以波浪号开始,则不更改返回路径。

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}.
Changed in version 3.6: Accepts a path-like object.

返回展开环境变量的参数。表单$name或${name}的子字符串被环境变量name的值替换。格式不正确的变量名和对不存在变量的引用保持不变。
在Windows上,除了$name和${name}之外,还支持%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 module). Raise OSError if the file does not exist or is inaccessible.

返回路径最后一次访问的时间。返回值是一个浮点数,给出从历元开始的秒数(参见时间模块)。如果文件不存在或无法访问,则引发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 module). Raise OSError if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object.

返回路径上次修改的时间。返回值是一个浮点数,给出从历元开始的秒数(参见时间模块)。如果文件不存在或无法访问,则引发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 module). Raise OSError if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object.

返回系统的ctime,在某些系统(如Unix)上,ctime是最后一次元数据更改的时间,在其他系统(如Windows)上,ctime是path的创建时间。返回值是一个数字,给出从历元开始的秒数(参见时间模块)。如果文件不存在或无法访问,则引发OSError。
在3.6版中更改:接受一个类似路径的对象。

os.path.getsize(path)
Return the size, in bytes, of path. Raise OSError if the file does not exist or is inaccessible.
Changed in version 3.6: Accepts a path-like object.

返回路径的大小(以字节为单位)。如果文件不存在或无法访问,则引发OSError。
在3.6版中更改:接受一个类似路径的对象。

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.
Changed in version 3.6: Accepts a path-like object.

如果path是绝对路径名,则返回True。在Unix上,这意味着它以斜杠开头;在Windows上,它以(反)斜杠开头,在截断一个可能的驱动器字母之后。
在3.6版中更改:接受一个类似路径的对象。

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.
Changed in version 3.6: Accepts a path-like object.

如果path是一个现有的常规文件,则返回True。这遵循符号链接,因此islink()和isfile()对于同一路径都可以为真。
在3.6版中更改:接受一个类似路径的对象。

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.
Changed in version 3.6: Accepts a path-like object.

如果path是现有目录,则返回True。这遵循符号链接,因此islink()和isdir()对于同一路径都可以为真。
在3.6版中更改:接受一个类似路径的对象。

os.path.islink(path)
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.
Changed in version 3.6: Accepts a path-like object.

如果path引用的是一个符号链接,则返回True。如果Python运行时不支持符号链接,则始终为False。
在3.6版中更改:接受一个类似路径的对象。

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.
New in version 3.4: Support for detecting non-root mount points on Windows.
Changed in version 3.6: Accepts a path-like object.

如果pathname path是一个挂载点,则返回True:挂载了不同文件系统的文件系统中的一个点。在POSIX上,函数检查path的父路径path/..,在与path不同的设备上,或者path/..路径指向同一设备上的同一i节点——这应该可以检测所有Unix和POSIX变体的挂载点。它不能可靠地检测同一文件系统上的绑定挂载。在Windows上,驱动器字母根和共享UNC始终是挂载点,对于任何其他路径,都会调用GetVolumePathName来查看它是否与输入路径不同。
新版本3.4:支持检测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 (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.
Changed in version 3.6: Accepts a path-like object for path and paths.

智能地连接一个或多个路径组件。返回值是path和*paths的所有成员的连接,除了最后一个部分之外,每个非空部分后面都有一个目录分隔符(os.sep),这意味着只有当最后一个部分是空的时候,结果才会以分隔符结束。如果一个组件是绝对路径,则丢弃所有以前的组件,并继续从绝对路径组件进行连接。
在Windows上,当遇到绝对路径组件(例如r'\foo')时,驱动器字母不会重置。如果一个组件包含一个驱动器号,则丢弃所有以前的组件并重置驱动器号。注意,由于每个驱动器都有一个当前目录os.path。join("c:", "foo")表示驱动器c: (c:foo)上相对于当前目录的路径,而不是c:\foo。
版本3.6中更改:接受path和paths的类路径对象。

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 is not str or bytes (directly or indirectly through the os.PathLike interface).
Changed in version 3.6: Accepts a path-like object.

将路径名的大小写规范化。在Unix和Mac OS X上,这将返回未更改的路径;在不区分大小写的文件系统上,它将路径转换为小写。在Windows上,它还将前斜杠转换为后斜杠。如果路径类型不是str或字节(直接或间接通过操作系统),则引发类型错误。PathLike接口)。
在3.6版中更改:接受一个类似路径的对象。

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().
Changed in version 3.6: Accepts a path-like object.

通过折叠冗余分隔符和上层引用来规范化路径名,以便a //B、a /B/、a /。/ B和A / foo / . ./B都变成了A/B。此字符串操作可能会更改包含符号链接的路径的含义。在Windows上,它将前斜杠转换为后斜杠。若要规范化大小写,请使用normcase()。
在3.6版中更改:接受一个类似路径的对象。

os.path.realpath(path)
Return the canonical path of the specified filename, eliminating any symbolic links encountered in the path (if they are supported by the operating system).
Changed in version 3.6: Accepts a path-like object.

返回指定文件名的规范路径,消除路径中遇到的任何符号链接(如果操作系统支持这些符号链接)。
在3.6版中更改:接受一个类似路径的对象。

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.
start defaults to os.curdir.
Availability: Unix, Windows.
Changed in version 3.6: Accepts a path-like object.

从当前目录或可选的开始目录返回到路径的相对文件路径。这是一个路径计算:没有访问文件系统来确认路径或启动的存在性或本质。
start默认为os.curdir。
可用性:Unix、Windows。
在3.6版中更改:接受一个类似路径的对象。

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.
Availability: Unix, Windows.
Changed in version 3.2: Added Windows support.
Changed in version 3.4: Windows now uses the same implementation as all other platforms.
Changed in version 3.6: Accepts a path-like object.

如果两个路径名参数都指向同一个文件或目录,则返回True。这是由设备号和i-node号决定的,如果对任一路径名的os.stat()调用失败,就会引发异常。
可用性:Unix、Windows。
在3.2版中更改:增加了Windows支持。
3.4版本的改变:Windows现在使用与所有其他平台相同的实现。
在3.6版中更改:接受一个类似路径的对象。

os.path.sameopenfile(fp1, fp2)
Return True if the file descriptors fp1 and fp2 refer to the same file.
Availability: Unix, Windows.
Changed in version 3.2: Added Windows support.
Changed in version 3.6: Accepts a path-like object.

如果文件描述符fp1和fp2指向同一个文件,则返回True。
可用性:Unix、Windows。
在3.2版中更改:增加了Windows支持。
在3.6版中更改:接受一个类似路径的对象。

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().
Availability: Unix, Windows.
Changed in version 3.4: Added Windows support.
Changed in version 3.6: Accepts a path-like object.

如果stat元组stat1和stat2引用同一个文件,则返回True。这些结构可能由os.fstat()、os.lstat()或os.stat()返回。此函数实现samefile()和sameopenfile()使用的底层比较。
可用性:Unix、Windows。
在3.4版中更改:增加了Windows支持。
在3.6版中更改:接受一个类似路径的对象。

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().
Changed in version 3.6: Accepts a path-like object.

将路径名路径分割成一对(head, tail), tail是最后一个路径名组件,head是指向该组件的所有内容。尾部永远不会包含斜线;如果路径以斜线结束,则tail为空。如果路径中没有斜杠,则磁头为空。如果路径是空的,那么头和尾都是空的。尾斜杠从头部移除,除非它是根(只有一个或多个斜杠)。在所有情况下,join(head, tail)都返回与path相同位置的路径(但是字符串可能不同)。还请参见函数dirname()和basename()。
在3.6版中更改:接受一个类似路径的对象。

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. e.g. splitdrive("c:/dir") returns ("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") returns ("//host/computer", "/dir")
Changed in version 3.6: Accepts a path-like object.

将路径名路径拆分为一对(驱动器、tail),其中驱动器要么是挂载点,要么是空字符串。在不使用驱动器规范的系统上,驱动器总是空字符串。在所有情况下,drive + tail将与path相同。
在Windows上,将路径名拆分为驱动器/UNC sharepoint和相对路径。
如果路径包含一个驱动器字母,驱动器将包含到冒号之前的所有内容。例如:splitdrive("c:/dir")返回("c:", "/dir")
如果路径包含UNC路径,驱动器将包含主机名和共享,直到但不包括第四个分隔符。例如:splitdrive("//host/computer/dir")返回("//host/computer", "/dir")
在3.6版中更改:接受一个类似路径的对象。

os.path.splitext(path)
Split the pathname path into a pair (root, ext) such that root + ext == path, and ext is empty or begins with a period and contains at most one period. Leading periods on the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').
Changed in version 3.6: Accepts a path-like object.

将路径名路径拆分为一对(root, ext),这样root + ext == path和ext为空,或者以句点开头,最多包含一个句点。基本名上的前导周期被忽略;splitext (。cshrc文件中)返回(“。cshrc’,”)。
在3.6版中更改:接受一个类似路径的对象。

os.path.supports_unicode_filenames
True if arbitrary Unicode strings can be used as file names (within limitations imposed by the file system).
如果任意Unicode字符串可以用作文件名(在文件系统施加的限制范围内),则为真。