16.1.5.文件和目录¶
在某些 Unix 平台上,许多函数支持以下一项或多项功能:
specifying a file descriptor:
For some functions, the path argument can be not only a string giving a path
name, but also a file descriptor. The function will then operate on the file
referred to by the descriptor. (For POSIX systems, Python will call the
f... version of the function.)
You can check whether or not path can be specified as a file descriptor on
your platform using os.supports_fd. If it is unavailable, using it
will raise a NotImplementedError.
If the function also supports dir_fd or follow_symlinks arguments, it is
an error to specify one of those when supplying path as a file descriptor.
paths relative to directory descriptors: If dir_fd is not None, it
should be a file descriptor referring to a directory, and the path to operate
on should be relative; path will then be relative to that directory. If the
path is absolute, dir_fd is ignored. (For POSIX systems, Python will call
the ...at or f...at version of the function.)
You can check whether or not dir_fd is supported on your platform using
os.supports_dir_fd. If it is unavailable, using it will raise a
NotImplementedError.
not following symlinks: If follow_symlinks is
False, and the last element of the path to operate on is a symbolic link,
the function will operate on the symbolic link itself instead of the file the
link points to. (For POSIX systems, Python will call the l... version of
the function.)
You can check whether or not follow_symlinks is supported on your platform
using os.supports_follow_symlinks. If it is unavailable, using it
will raise a NotImplementedError.
os.access(path, mode, *, dir_fd=None, effective_ids=False, follow_symlinks=True)¶
使用真实的 uid/gid 测试对 path 的访问。请注意,大多数测试操作将使用有效的 uid/gid,因此可以在 suid/sgid 环境中运用此例程,来测试调用用户是否具有对 path 的指定访问权限。mode 为 F_OK 时用于测试 path 是否存在,也可以对 R_OK、W_OK 和 X_OK 中的一个或多个进行“或”运算来测试指定权限。允许访问则返回 True,否则返回 False。更多信息请参见 Unix 手册页 access(2)。
如果 effective_ids 为 True,access() 将使用 有效用户ID/用户组ID 而非 实际用户ID/用户组ID 进行访问检查。您的平台可能不支持 effective_ids,您可以使用 os.supports_effective_ids 检查它是否可用。如果不可用,使用它时会抛出 NotImplementedError 异常。
備註
使用 access() 来检查用户是否具有某项权限(如打开文件的权限),然后再使用 open() 打开文件,这样做存在一个安全漏洞,因为用户可能会在检查和打开文件之间的时间里做其他操作。推荐使用 EAFP 技术。如:
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
return "some default data"
最好写成:
try:
fp = open("myfile")
except PermissionError:
return "some default data"
else:
with fp:
return fp.read()
備註
即使 access() 指示 I/O 操作会成功,但实际操作仍可能失败,尤其是对网络文件系统的操作,其权限语义可能超出常规的 POSIX 权限位模型。
3.3 版更變:添加 dir_fd、effective_ids 和 follow_symlinks 参数。
os.F_OK¶
os.R_OK¶
os.W_OK¶
os.X_OK¶
作为 access() 的 mode 参数的可选值,分别测试 path 的存在性、可读性、可写性和可执行性。
os.chdir(path)¶
将当前工作目录更改为 path。
本函数支持 指定文件描述符为参数。其中,描述符必须指向打开的目录,不能是打开的文件。
3.3 版新加入:在某些平台上新增支持将 path 参数指定为文件描述符。
os.chown(path, uid, gid, *, dir_fd=None, follow_symlinks=True)¶
将 path 的用户和组 ID 分别修改为数字形式的 uid 和 gid。若要使其中某个 ID 保持不变,请将其置为 -1。
参见更高阶的函数 shutil.chown(),除了数字 ID 之外,它也接受名称。
Availability: Unix.
3.3 版新加入:Added support for specifying an open file descriptor for path,
and the dir_fd and follow_symlinks arguments.
3.6 版更變:支持 类路径对象。
os.chroot(path)¶
将当前进程的根目录更改为 path。
Availability: Unix.
os.fchdir(fd)¶
将当前工作目录更改为文件描述符 fd 指向的目录。fd 必须指向打开的目录而非文件。从 Python 3.3 开始,它等效于 os.chdir(fd)。
Availability: Unix.
os.getcwd()¶
返回表示当前工作目录的字符串。
os.getcwdb()¶
返回表示当前工作目录的字节串 (bytestring)。
os.lchflags(path, flags)¶
将 path 的 flags 设置为其他由数字表示的 flags,与 chflags() 类似,但不跟踪符号链接。从 Python 3.3 开始,它等效于 os.chflags(path, flags, follow_symlinks=False)。
Availability: Unix.
os.lchmod(path, mode)¶
将 path 的权限状态修改为 mode。如果 path 是符号链接,则影响符号链接本身而非链接目标。可以参考 chmod() 中列出 mode 的可用值。从 Python 3.3 开始,这相当于 os.chmod(path, mode, follow_symlinks=False)。
Availability: Unix.
os.lchown(path, uid, gid)¶
将 path 的用户和组 ID 分别修改为数字形式的 uid 和 gid,本函数不跟踪符号链接。从 Python 3.3 开始,它等效于 os.chown(path, uid, gid, follow_symlinks=False)。
Availability: Unix.
os.link(src, dst, *, src_dir_fd=None, dst_dir_fd=None, follow_symlinks=True)¶
创建一个指向 src 的硬链接,名为 dst。
本函数支持将 src_dir_fd 和 dst_dir_fd 中的一个或两个指定为 基于目录描述符的相对路径,支持 不跟踪符号链接。
Availability: Unix, Windows.
3.2 版更變:添加了Windows 支持
3.3 版新加入:添加 src_dir_fd、dst_dir_fd 和 follow_symlinks 参数。
3.6 版更變:接受一个 类路径对象 作为 src 和 dst。
os.listdir(path='.')¶
返回一个列表,该列表包含了 path 中所有文件与目录的名称。该列表按任意顺序排列,并且不包含特殊条目 '.' 和 '..',即使它们确实在目录中存在。
path 可以是 路径类对象。如果 path 是(直接/间接由 PathLike 接口返回的) bytes 类型,则返回的文件名也将是 bytes 类型,其他情况下文件名类型是 str。
本函数也支持 指定文件描述符为参数,其中描述符必须指向目录。
備註
要将 str 类型的文件名编码为 bytes,请使用 fsencode()。
也參考
scandir() 函数返回目录内文件名的同时,也返回文件属性信息,它在某些具体情况下能提供更好的性能。
3.2 版更變:path 变为可选参数。
3.3 版新加入:Added support for specifying an open file descriptor for path.
os.lstat(path, *, dir_fd=None)¶
在给定路径上执行本函数,其操作相当于 lstat() 系统调用,类似于 stat() 但不跟踪符号链接。返回值是 stat_result 对象。
在不支持符号链接的平台上,本函数是 stat() 的别名。
从 Python 3.3 起,此功能等价于 os.stat(path, dir_fd=dir_fd, follow_symlinks=False)。
也參考
3.2 版更變:添加对 Windows 6.0 (Vista) 符号链接的支持。
3.3 版更變:添加了 dir_fd 参数。
3.6 版更變:接受一个 类路径对象 作为 src 和 dst。
os.mkdir(path, mode=0o777, *, dir_fd=None)¶
创建一个名为 path 的目录,应用以数字表示的权限模式 mode。
某些系统会忽略 mode。如果没有忽略它,那么将首先从它中减去当前的 umask 值。如果除最后 9 位(即 mode 八进制的最后 3 位)之外,还设置了其他位,则其他位的含义取决于各个平台。在某些平台上,它们会被忽略,应显式调用 chmod() 进行设置。
3.3 版新加入:dir_fd 参数。
os.makedirs(name, mode=0o777, exist_ok=False)¶
递归目录创建函数。与 mkdir() 类似,但会自动创建到达最后一级目录所需要的中间目录。
The mode parameter is passed to mkdir(); see the mkdir()
description for how it is interpreted.
If exist_ok is False (the default), an OSError is raised if the
target directory already exists.
備註
如果要创建的路径元素包含 pardir (如 UNIX 系统中的 「..」) makedirs() 将无法明确目标。
本函数能正确处理 UNC 路径。
3.2 版新加入:exist_ok 参数。
3.4.1 版更變:在 Python 3.4.1 以前,如果 exist_ok 为 True,且目录已存在,且 mode 与现有目录的权限不匹配,makedirs() 仍会抛出错误。由于无法安全地实现此行为,因此在 Python 3.4.1 中将该行为删除。请参阅 bpo-21082。
os.mkfifo(path, mode=0o666, *, dir_fd=None)¶
创建一个名为 path 的 FIFO(命名管道,一种先进先出队列),具有以数字表示的权限状态 mode。将从 mode 中首先减去当前的 umask 值。
FIFO 是可以像常规文件一样访问的管道。FIFO 如果没有被删除(如使用 os.unlink()),会一直存在。通常,FIFO 用作“客户端”和“服务器”进程之间的汇合点:服务器打开 FIFO 进行读取,而客户端打开 FIFO 进行写入。请注意,mkfifo() 不会打开 FIFO — 它只是创建汇合点。
Availability: Unix.
3.3 版新加入:dir_fd 参数。
os.mknod(path, mode=0o600, device=0, *, dir_fd=None)¶
创建一个名为 path 的文件系统节点(文件,设备专用文件或命名管道)。mode 指定权限和节点类型,方法是将权限与下列节点类型 stat.S_IFREG、stat.S_IFCHR、stat.S_IFBLK 和 stat.S_IFIFO 之一(按位或)组合(这些常量可以在 stat 模块中找到)。对于 stat.S_IFCHR 和 stat.S_IFBLK,device 参数指定了新创建的设备专用文件(可能会用到 os.makedev()),否则该参数将被忽略。
Availability: Unix.
3.3 版新加入:dir_fd 参数。
os.major(device)¶
提取主设备号,提取自原始设备号(通常是 stat 中的 st_dev 或 st_rdev 字段)。
os.minor(device)¶
提取次设备号,提取自原始设备号(通常是 stat 中的 st_dev 或 st_rdev 字段)。
os.makedev(major, minor)¶
将主设备号和次设备号组合成原始设备号。
os.pathconf(path, name)¶
返回所给名称的文件有关的系统配置信息。name 指定要查找的配置名称,它可以是字符串,是一个系统已定义的名称,这些名称定义在不同标准(POSIX.1,Unix 95,Unix 98 等)中。一些平台还定义了额外的其他名称。当前操作系统已定义的名称在 pathconf_names 字典中给出。对于未包含在该映射中的配置名称,也可以传递一个整数作为 name。
如果 name 是一个字符串且不是已定义的名称,将抛出 ValueError 异常。如果当前系统不支持 name 指定的配置名称,即使该名称存在于 pathconf_names,也会抛出 OSError 异常,错误码为 errno.EINVAL。
Availability: Unix.
os.pathconf_names¶
字典,表示映射关系,为 pathconf() 和 fpathconf() 可接受名称与操作系统为这些名称定义的整数值之间的映射。这可用于判断系统已定义了哪些名称。
Availability: Unix.
os.readlink(path, *, dir_fd=None)¶
返回一个字符串,为符号链接指向的实际路径。其结果可以是绝对或相对路径。如果是相对路径,则可用 os.path.join(os.path.dirname(path), result) 转换为绝对路径。
如果 path 是字符串对象(直接传入或通过 PathLike 接口间接传入),则结果也将是字符串对象,且此类调用可能会引发 UnicodeDecodeError。如果 path 是字节对象(直接传入或间接传入),则结果将会是字节对象。
Availability: Unix, Windows
3.2 版更變:添加对 Windows 6.0 (Vista) 符号链接的支持。
3.3 版新加入:dir_fd 参数。
os.remove(path, *, dir_fd=None)¶
Remove (delete) the file path. If path is a directory, OSError is
raised. Use rmdir() to remove directories.
在 Windows 上,尝试删除正在使用的文件会抛出异常。而在 Unix 上,虽然该文件的条目会被删除,但分配给文件的存储空间仍然不可用,直到原始文件不再使用为止。
本函数在语义上与 unlink() 相同。
3.3 版新加入:dir_fd 参数。
os.removedirs(name)¶
递归删除目录。工作方式类似于 rmdir(),不同之处在于,如果成功删除了末尾一级目录,removedirs() 会尝试依次删除 path 中提到的每个父目录,直到抛出错误为止(但该错误会被忽略,因为这通常表示父目录不是空目录)。例如,os.removedirs('foo/bar/baz') 将首先删除目录 'foo/bar/baz',然后如果 'foo/bar' 和 'foo' 为空,则继续删除它们。如果无法成功删除末尾一级目录,则抛出 OSError 异常。
os.rename(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
Rename the file or directory src to dst. If dst is a directory,
OSError will be raised. On Unix, if dst exists and is a file, it will
be replaced silently if the user has permission. The operation may fail on some
Unix flavors if src and dst are on different filesystems. If successful,
the renaming will be an atomic operation (this is a POSIX requirement). On
Windows, if dst already exists, OSError will be raised even if it is a
file.
本函数支持将 src_dir_fd 和 dst_dir_fd 中的一个或两个指定为 基于目录描述符的相对路径。
如果需要在不同平台上都能替换目标,请使用 replace()。
3.3 版新加入:src_dir_fd 和 dst_dir_fd 参数。
3.6 版更變:接受一个 类路径对象 作为 src 和 dst。
os.renames(old, new)¶
递归重命名目录或文件。工作方式类似 rename(),除了会首先创建新路径所需的中间目录。重命名后,将调用 removedirs() 删除旧路径中不需要的目录。
備註
如果用户没有权限删除末级的目录或文件,则本函数可能会无法建立新的目录结构。
3.6 版更變:接受一个 类路径对象 作为 old 和 new。
os.replace(src, dst, *, src_dir_fd=None, dst_dir_fd=None)¶
将文件或目录 src 重命名为 dst。如果 dst 是目录,将抛出 OSError 异常。如果 dst 已存在且为文件,则在用户具有权限的情况下,将对其进行静默替换。如果 src 和 dst 在不同的文件系统上,本操作可能会失败。如果成功,重命名操作将是一个原子操作(这是 POSIX 的要求)。
本函数支持将 src_dir_fd 和 dst_dir_fd 中的一个或两个指定为 基于目录描述符的相对路径。
3.3 版新加入.
3.6 版更變:接受一个 类路径对象 作为 src 和 dst。
os.rmdir(path, *, dir_fd=None)¶
Remove (delete) the directory path. Only works when the directory is
empty, otherwise, OSError is raised. In order to remove whole
directory trees, shutil.rmtree() can be used.
3.3 版新加入:dir_fd 参数。
os.scandir(path='.')¶
返回一个迭代出 os.DirEntry 对象的迭代器,这些对象对应于 path 目录中的条目。条目的生成顺序是任意的,特殊条目 '.' 和 '..' 不包括在内。
如果需要文件类型或文件属性信息,使用 scandir() 代替 listdir() 可以大大提高这部分代码的性能,因为如果操作系统在扫描目录时返回的是 os.DirEntry 对象,则该对象包含了这些信息。所有 os.DirEntry 的方法都可能执行一次系统调用,但是 is_dir() 和 is_file() 通常只在有符号链接时才执行一次系统调用。os.DirEntry.stat() 在 Unix 上始终需要一次系统调用,而在 Windows 上只在有符号链接时才需要。
path 可以是 类路径对象。如果 path 是(直接/间接由 PathLike 接口返回的)``bytes`` 类型,那么每个 os.DirEntry 的 name 和 path 属性将是 bytes 类型,其他情况下是 str 类型。
scandir() 迭代器支持 上下文管理 协议,并具有以下方法:
scandir.close()¶
关闭迭代器并释放占用的资源。
当迭代器迭代完毕,或垃圾回收,或迭代过程出错时,将自动调用本方法。但仍建议显式调用它或使用 with 语句。
3.6 版新加入.
下面的例子演示了 scandir() 的简单用法,用来显示给定 path 中所有不以 '.' 开头的文件(不包括目录)。entry.is_file() 通常不会增加一次额外的系统调用:
with os.scandir(path) as it:
for entry in it:
if not entry.name.startswith('.') and entry.is_file():
print(entry.name)
3.5 版新加入.
3.6 版新加入:添加了对 上下文管理 协议和 close() 方法的支持。如果 scandir() 迭代器没有迭代完毕且没有显式关闭,其析构函数将发出 ResourceWarning 警告。
本函数接受一个 类路径对象。
classos.DirEntry¶
由 scandir() 产生的对象,用于显示目录内某个条目的文件路径和其他文件属性。
scandir() 将在不进行额外系统调用的情况下,提供尽可能多的此类信息。每次进行 stat() 或 lstat() 系统调用时,os.DirEntry 对象会将结果缓存下来。
os.DirEntry 实例不适合存储在长期存在的数据结构中,如果你知道文件元数据已更改,或者自调用 scandir() 以来已经经过了很长时间,请调用 os.stat(entry.path) 来获取最新信息。
因为 os.DirEntry 方法可以进行系统调用,所以它也可能抛出 OSError 异常。如需精确定位错误,可以逐个调用 os.DirEntry 中的方法来捕获 OSError,并适当处理。
为了能直接用作 类路径对象,os.DirEntry 实现了 PathLike 接口。
os.DirEntry 实例所包含的属性和方法如下:
name¶
本条目的基本文件名,是根据 scandir() 的 path 参数得出的相对路径。
如果 scandir() 的 path 参数是 bytes 类型,则 name 属性也是 bytes 类型,否则为 str。使用 fsdecode() 解码 byte 类型的文件名。
path¶
The entry’s full path name: equivalent to os.path.join(scandir_path,
entry.name) where scandir_path is the scandir() path
argument. The path is only absolute if the scandir() path
argument was absolute.
如果 scandir() 的 path 参数是 bytes 类型,则 path 属性也是 bytes 类型,否则为 str。使用 fsdecode() 解码 byte 类型的文件名。
inode()¶
返回本条目的索引节点号。
这一结果是缓存在 os.DirEntry 对象中的,请调用 os.stat(entry.path, follow_symlinks=False).st_ino 来获取最新信息。
一开始没有缓存时,在 Windows 上需要一次系统调用,但在 Unix 上不需要。
is_dir(*, follow_symlinks=True)¶
如果本条目是目录,或是指向目录的符号链接,则返回 True。如果本条目是文件,或指向任何其他类型的文件,或该文件不再存在,则返回 False。
如果 follow_symlinks 是 False,那么仅当本条目为目录时返回 True``(不跟踪符号链接),如果本条目是任何类型的文件,或该文件不再存在,则返回 ``False。
这一结果是缓存在 os.DirEntry 对象中的,且 follow_symlinks 为 True 和 False 时的缓存是分开的。请调用 os.stat() 和 stat.S_ISDIR() 来获取最新信息。
一开始没有缓存时,大多数情况下不需要系统调用。特别是对于非符号链接,Windows 和 Unix 都不需要系统调用,除非某些 Unix 文件系统(如网络文件系统)返回了 dirent.d_type == DT_UNKNOWN。如果本条目是符号链接,则需要一次系统调用来跟踪它(除非 follow_symlinks 为 False)。
is_file(*, follow_symlinks=True)¶
如果本条目是文件,或是指向文件的符号链接,则返回 True。如果本条目是目录,或指向目录,或指向其他非文件条目,或该文件不再存在,则返回 False。
如果 follow_symlinks 是 False,那么仅当本条目为文件时返回 True``(不跟踪符号链接),如果本条目是目录或其他非文件条目,或该文件不再存在,则返回 ``False。
这一结果是缓存在 os.DirEntry 对象中的。缓存、系统调用、异常抛出都与 is_dir() 一致。
is_symlink()¶
如果本条目是符号链接(即使是断开的链接),返回 True。如果是目录或任何类型的文件,或本条目不再存在,返回 False。
这一结果是缓存在 os.DirEntry 对象中的,请调用 os.path.islink() 来获取最新信息。
一开始没有缓存时,大多数情况下不需要系统调用。其实 Windows 和 Unix 都不需要系统调用,除非某些 Unix 文件系统(如网络文件系统)返回了 dirent.d_type == DT_UNKNOWN。
stat(*, follow_symlinks=True)¶
返回本条目对应的 stat_result 对象。本方法默认会跟踪符号链接,要获取符号链接本身的 stat,请添加 follow_symlinks=False 参数。
On Unix, this method always requires a system call. On Windows, it
only requires a system call if follow_symlinks is True and the
entry is a symbolic link.
在 Windows 上,stat_result 的 st_ino、st_dev 和 st_nlink 属性总是为零。请调用 os.stat() 以获得这些属性。
这一结果是缓存在 os.DirEntry 对象中的,且 follow_symlinks 为 True 和 False 时的缓存是分开的。请调用 os.stat() 来获取最新信息。
注意,os.DirEntry 和 pathlib.Path 的几个属性和方法之间存在很好的对应关系。具体来说是 name 属性,以及 is_dir()、is_file()、is_symlink() 和 stat() 方法,在两个类中具有相同的含义。
3.5 版新加入.
3.6 版更變:添加了对 PathLike 接口的支持。在 Windows 上添加了对 bytes 类型路径的支持。
os.stat(path, *, dir_fd=None, follow_symlinks=True)¶
获取文件或文件描述符的状态。在所给路径上执行等效于 stat() 系统调用的操作。path 可以是字符串类型,或(直接/间接由 PathLike 接口返回的) bytes 类型,或打开的文件描述符。返回一个 stat_result 对象。
本函数默认会跟踪符号链接,要获取符号链接本身的 stat,请添加 follow_symlinks=False 参数,或使用 lstat()。
示例:
>>>import os
>>>statinfo = os.stat('somefile.txt')
>>>statinfo
os.stat_result(st_mode=33188, st_ino=7876932, st_dev=234881026,
st_nlink=1, st_uid=501, st_gid=501, st_size=264, st_atime=1297230295,
st_mtime=1297230027, st_ctime=1297230027)
>>>statinfo.st_size
264
3.3 版新加入:增加 dir_fd 和 follow_symlinks 参数,可指定文件描述符代替路径。
classos.stat_result¶
本对象的属性大致对应于 stat 结构体成员,主要作为 os.stat()、os.fstat() 和 os.lstat() 的返回值。
属性:
st_mode¶
文件模式:包括文件类型和文件模式位(即权限位)。
st_ino¶
与平台有关,但如果不为零,则根据 st_dev 值唯一地标识文件。通常:
在 Unix 上该值表示索引节点号 (inode number)。
在 Windows 上该值表示 文件索引号 。
st_dev¶
该文件所在设备的标识符。
st_nlink¶
硬链接的数量。
st_uid¶
文件所有者的用户 ID。
st_gid¶
文件所有者的用户组 ID。
st_size¶
文件大小(以字节为单位),文件可以是常规文件或符号链接。符号链接的大小是它包含的路径的长度,不包括末尾的空字节。
时间戳:
st_atime¶
最近的访问时间,以秒为单位。
st_mtime¶
最近的修改时间,以秒为单位。
st_ctime¶
取决于平台:
在 Unix 上表示最近的元数据更改时间,
在 Windows 上表示创建时间,以秒为单位。
st_atime_ns¶
最近的访问时间,以纳秒表示,为整数。
st_mtime_ns¶
最近的修改时间,以纳秒表示,为整数。
st_ctime_ns¶
取决于平台:
在 Unix 上表示最近的元数据更改时间,
在 Windows 上表示创建时间,以纳秒表示,为整数。
See also the stat_float_times() function.
備註
st_atime、st_mtime 和 st_ctime 属性的确切含义和分辨率取决于操作系统和文件系统。例如,在使用 FAT 或 FAT32 文件系统的 Windows 上,st_mtime 有 2 秒的分辨率,而 st_atime 仅有 1 天的分辨率。详细信息请参阅操作系统文档。
类似地,尽管 st_atime_ns、st_mtime_ns 和 st_ctime_ns 始终以纳秒表示,但许多系统并不提供纳秒精度。在确实提供纳秒精度的系统上,用于存储 st_atime、st_mtime 和 st_ctime 的浮点对象无法保留所有精度,因此不够精确。如果需要确切的时间戳,则应始终使用 st_atime_ns、st_mtime_ns 和 st_ctime_ns。
在某些 Unix 系统上(如 Linux 上),以下属性可能也可用:
st_blocks¶
为文件分配的字节块数,每块 512 字节。文件是稀疏文件时,它可能小于 st_size/512。
st_blksize¶
“首选的” 块大小,用于提高文件系统 I/O 效率。写入文件时块大小太小可能会导致读取-修改-重写效率低下。
st_rdev¶
设备类型(如果是 inode 设备)。
st_flags¶
用户定义的文件标志位。
在其他 Unix 系统上(如 FreeBSD 上),以下属性可能可用(但仅当 root 使用它们时才被填充):
st_gen¶
文件生成号。
st_birthtime¶
文件创建时间。
在 Mac OS 系统上,以下属性可能也可用:
st_rsize¶
文件的实际大小。
st_creator¶
文件的创建者。
st_type¶
文件类型。
On Windows systems, the following attribute is also available:
st_file_attributes¶
Windows 文件属性:dwFileAttributes,由 GetFileInformationByHandle() 返回的 BY_HANDLE_FILE_INFORMATION 结构体的成员之一。请参阅 stat 模块中的 FILE_ATTRIBUTE_* 常量。
标准模块 stat 中定义了函数和常量,这些函数和常量可用于从 stat 结构体中提取信息。(在 Windows 上,某些项填充的是虚值。)
为了向后兼容,一个 stat_result 实例还可以作为至少包含 10 个整数的元组访问,以提供 stat 结构中最重要(和可移植)的成员,整数顺序为 st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime。某些实现可能在末尾还有更多项。为了与旧版 Python 兼容,以元组形式访问 stat_result 始终返回整数。
3.5 版新加入:在 Windows 上添加了 st_file_attributes 成员。
3.5 版更變:在 Windows 上,如果可用,会返回文件索引作为 st_ino 的值。
os.stat_float_times([newvalue])¶
Determine whether stat_result represents time stamps as float objects.
If newvalue is True, future calls to stat() return floats, if it is
False, future calls return ints. If newvalue is omitted, return the
current setting.
For compatibility with older Python versions, accessing stat_result as
a tuple always returns integers.
Python now returns float values by default. Applications which do not work
correctly with floating point time stamps can use this function to restore the
old behaviour.
The resolution of the timestamps (that is the smallest possible fraction)
depends on the system. Some systems only support second resolution; on these
systems, the fraction will always be zero.
It is recommended that this setting is only changed at program startup time in
the __main__ module; libraries should never change this setting. If an
application uses a library that works incorrectly if floating point time stamps
are processed, this application should turn the feature off until the library
has been corrected.
3.3 版後已棄用.
os.statvfs(path)¶
Perform a statvfs() system call on the given path. The return value is
an object whose attributes describe the filesystem on the given path, and
correspond to the members of the statvfs structure, namely:
f_bsize, f_frsize, f_blocks, f_bfree,
f_bavail, f_files, f_ffree, f_favail,
f_flag, f_namemax.
为 f_flag 属性位定义了两个模块级常量:如果存在 ST_RDONLY 位,则文件系统以只读挂载;如果存在 ST_NOSUID 位,则文件系统禁用或不支持 setuid/setgid 位。
为基于 GNU/glibc 的系统还定义了额外的模块级常量。它们是 ST_NODEV (禁止访问设备专用文件),ST_NOEXEC (禁止执行程序),ST_SYNCHRONOUS (写入后立即同步),ST_MANDLOCK (允许文件系统上的强制锁定),ST_WRITE (写入文件/目录/符号链接),ST_APPEND (仅追加文件),ST_IMMUTABLE (不可变文件),ST_NOATIME (不更新访问时间),ST_NODIRATIME (不更新目录访问时间),ST_RELATIME (相对于 mtime/ctime 更新访问时间)。
Availability: Unix.
3.2 版更變:添加了 ST_RDONLY 和 ST_NOSUID 常量。
3.3 版新加入:Added support for specifying an open file descriptor for path.
3.4 版更變:添加了 ST_NODEV、ST_NOEXEC、ST_SYNCHRONOUS、ST_MANDLOCK、ST_WRITE、ST_APPEND、ST_IMMUTABLE、ST_NOATIME、ST_NODIRATIME 和 ST_RELATIME 常量。
os.supports_dir_fd¶
A Set object indicating which functions in the
os module permit use of their dir_fd parameter. Different platforms
provide different functionality, and an option that might work on one might
be unsupported on another. For consistency’s sakes, functions that support
dir_fd always allow specifying the parameter, but will raise an exception
if the functionality is not actually available.
To check whether a particular function permits use of its dir_fd
parameter, use the in operator on supports_dir_fd. As an example,
this expression determines whether the dir_fd parameter of os.stat()
is locally available:
os.stat in os.supports_dir_fd
目前 dir_fd 参数仅在 Unix 平台上有效,在 Windows 上均无效。
3.3 版新加入.
os.supports_effective_ids¶
A Set object indicating which functions in the
os module permit use of the effective_ids parameter for
os.access(). If the local platform supports it, the collection will
contain os.access(), otherwise it will be empty.
To check whether you can use the effective_ids parameter for
os.access(), use the in operator on supports_effective_ids,
like so:
os.access in os.supports_effective_ids
Currently effective_ids only works on Unix platforms; it does not work on
Windows.
3.3 版新加入.
os.supports_fd¶
A Set object indicating which functions in the
os module permit specifying their path parameter as an open file
descriptor. Different platforms provide different functionality, and an
option that might work on one might be unsupported on another. For
consistency’s sakes, functions that support fd always allow specifying
the parameter, but will raise an exception if the functionality is not
actually available.
To check whether a particular function permits specifying an open file
descriptor for its path parameter, use the in operator on
supports_fd. As an example, this expression determines whether
os.chdir() accepts open file descriptors when called on your local
platform:
os.chdir in os.supports_fd
3.3 版新加入.
os.supports_follow_symlinks¶
A Set object indicating which functions in the
os module permit use of their follow_symlinks parameter. Different
platforms provide different functionality, and an option that might work on
one might be unsupported on another. For consistency’s sakes, functions that
support follow_symlinks always allow specifying the parameter, but will
raise an exception if the functionality is not actually available.
To check whether a particular function permits use of its follow_symlinks
parameter, use the in operator on supports_follow_symlinks. As an
example, this expression determines whether the follow_symlinks parameter
of os.stat() is locally available:
os.stat in os.supports_follow_symlinks
3.3 版新加入.
os.symlink(src, dst, target_is_directory=False, *, dir_fd=None)¶
创建一个指向 src 的符号链接,名为 dst。
在 Windows 上,符号链接可以表示文件或目录两种类型,并且不会动态改变类型。如果目标存在,则新建链接的类型将与目标一致。否则,如果 target_is_directory 为 True,则符号链接将创建为目录链接,为 False (默认)将创建为文件链接。在非 Windows 平台上,target_is_directory 被忽略。
Symbolic link support was introduced in Windows 6.0 (Vista). symlink()
will raise a NotImplementedError on Windows versions earlier than 6.0.
備註
On Windows, the SeCreateSymbolicLinkPrivilege is required in order to
successfully create symlinks. This privilege is not typically granted to
regular users but is available to accounts which can escalate privileges
to the administrator level. Either obtaining the privilege or running your
application as an administrator are ways to successfully create symlinks.
当本函数由非特权账户调用时,抛出 OSError 异常。
Availability: Unix, Windows.
3.2 版更變:添加对 Windows 6.0 (Vista) 符号链接的支持。
3.3 版新加入:添加了 dir_fd 参数,现在在非 Windows 平台上允许 target_is_directory 参数。
3.6 版更變:接受一个 类路径对象 作为 src 和 dst。
os.sync()¶
强制将所有内容写入磁盘。
Availability: Unix.
3.3 版新加入.
os.truncate(path, length)¶
截断 path 对应的文件,以使其最大为 length 字节大小。
Availability: Unix, Windows.
3.3 版新加入.
3.5 版更變:添加了 Windows 支持
os.unlink(path, *, dir_fd=None)¶
移除(删除)文件 path。该函数在语义上与 remove() 相同,unlink 是其传统的 Unix 名称。请参阅 remove() 的文档以获取更多信息。
3.3 版新加入:dir_fd 参数。
os.utime(path, times=None, *, [ns, ]dir_fd=None, follow_symlinks=True)¶
设置文件 path 的访问时间和修改时间。
utime() 有 times 和 ns 两个可选参数,它们指定了设置给 path 的时间,用法如下:
如果指定 ns,它必须是一个 (atime_ns, mtime_ns) 形式的二元组,其中每个成员都是一个表示纳秒的整数。
如果 times 不为 None,则它必须是 (atime, mtime) 形式的二元组,其中每个成员都是一个表示秒的 int 或 float。
如果 times 为 None 且未指定 ns,则相当于指定 ns=(atime_ns, mtime_ns),其中两个时间均为当前时间。
同时为 times 和 ns 指定元组会出错。
Whether a directory can be given for path
depends on whether the operating system implements directories as files
(for example, Windows does not). Note that the exact times you set here may
not be returned by a subsequent stat() call, depending on the
resolution with which your operating system records access and modification
times; see stat(). The best way to preserve exact times is to
use the st_atime_ns and st_mtime_ns fields from the os.stat()
result object with the ns parameter to utime.
3.3 版新加入:Added support for specifying an open file descriptor for path,
and the dir_fd, follow_symlinks, and ns parameters.
os.walk(top, topdown=True, οnerrοr=None, followlinks=False)¶
生成目录树中的文件名,方式是按上->下或下->上顺序浏览目录树。对于以 top 为根的目录树中的每个目录(包括 top 本身),它都会生成一个三元组 (dirpath, dirnames, filenames)。
dirpath 是一个字符串,表示目录的路径。dirnames 是一个列表,内含 dirpath 中子目录的名称(不包括 '.' 和 '..' )。filenames 也是列表,内含 dirpath 中非目录文件的名称。注意,列表中的名称不包含路径部分。要获取 dirpath 中文件或目录的完整路径(从 top 起始),请执行 os.path.join(dirpath, name)。
如果可选参数 topdown 为 True 或未指定,则在所有子目录的三元组之前生成父目录的三元组(目录是自上而下生成的)。如果 topdown 为 False,则在所有子目录的三元组生成之后再生成父目录的三元组(目录是自下而上生成的)。无论 topdown 为何值,在生成目录及其子目录的元组之前,都将检索全部子目录列表。
当 topdown 为 True 时,调用者可以就地修改 dirnames 列表(也许用到了 del 或切片),而 walk() 将仅仅递归到仍保留在 dirnames 中的子目录内。这可用于减少搜索、加入特定的访问顺序,甚至可在继续 walk() 之前告知 walk() 由调用者新建或重命名的目录的信息。当 topdown 为 False 时,修改 dirnames 对 walk 的行为没有影响,因为在自下而上模式中,dirnames 中的目录是在 dirpath 本身之前生成的。
默认将忽略 scandir() 调用中的错误。如果指定了可选参数 onerror,它应该是一个函数。出错时它会被调用,参数是一个 OSError 实例。它可以报告错误然后继续遍历,或者抛出异常然后中止遍历。注意,可以从异常对象的 filename 属性中获取出错的文件名。
walk() 默认不会递归进指向目录的符号链接。可以在支持符号链接的系统上将 followlinks 设置为 True,以访问符号链接指向的目录。
備註
注意,如果链接指向自身的父目录,则将 followlinks 设置为 True 可能导致无限递归。walk() 不会记录它已经访问过的目录。
備註
如果传入的是相对路径,请不要在恢复 walk() 之间更改当前工作目录。walk() 不会更改当前目录,并假定其调用者也不会更改当前目录。
下面的示例遍历起始目录内所有子目录,打印每个目录内的文件占用的字节数,CVS 子目录不会被遍历:
import os
from os.path import join, getsize
for root, dirs, files in os.walk('python/Lib/email'):
print(root, "consumes", end=" ")
print(sum(getsize(join(root, name)) for name in files), end=" ")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
在下一个示例(shutil.rmtree() 的简单实现)中,必须使树自下而上,因为 rmdir() 只允许在目录为空时删除目录:
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
3.5 版更變:现在,本函数调用的是 os.scandir() 而不是 os.listdir(),从而减少了调用 os.stat() 的次数而变得更快。
os.fwalk(top='.', topdown=True, οnerrοr=None, *, follow_symlinks=False, dir_fd=None)¶
本方法的行为与 walk() 完全一样,除了它产生的是 4 元组 (dirpath, dirnames, filenames, dirfd),并且它支持 dir_fd。
dirpath、dirnames 和 filenames 与 walk() 输出的相同,dirfd 是指向目录 dirpath 的文件描述符。
本函数始终支持 基于目录描述符的相对路径 和 不跟踪符号链接。但是请注意,与其他函数不同,fwalk() 的 follow_symlinks 的默认值为 False。
備註
由于 fwalk() 会生成文件描述符,而它们仅在下一个迭代步骤前有效,因此如果要将描述符保留更久,则应复制它们(比如使用 dup())。
下面的示例遍历起始目录内所有子目录,打印每个目录内的文件占用的字节数,CVS 子目录不会被遍历:
import os
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
print(root, "consumes", end="")
print(sum([os.stat(name, dir_fd=rootfd).st_size for name in files]),
end="")
print("bytes in", len(files), "non-directory files")
if 'CVS' in dirs:
dirs.remove('CVS') # don't visit CVS directories
在下一个示例中,必须使树自下而上遍历,因为 rmdir() 只允许在目录为空时删除目录:
# Delete everything reachable from the directory named in "top",
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files, rootfd in os.fwalk(top, topdown=False):
for name in files:
os.unlink(name, dir_fd=rootfd)
for name in dirs:
os.rmdir(name, dir_fd=rootfd)
Availability: Unix.
3.3 版新加入.
16.1.5.1.Linux 扩展属性¶
3.3 版新加入.
这些函数仅在 Linux 上可用。
os.getxattr(path, attribute, *, follow_symlinks=True)¶
返回 path 的扩展文件系统属性 attribute 的值。attribute 可以是 bytes 或 str (直接/间接通过 PathLike 接口返回的)。如果是 str,则使用文件系统编码来编码字符串。
3.6 版更變:接受一个 类路径对象 作为 path 和 attribute。
os.listxattr(path=None, *, follow_symlinks=True)¶
返回一个列表,包含 path 的所有扩展文件系统属性。列表中的属性都表示为字符串,它们是根据文件系统编码解码出来的。如果 path 为 None,则 listxattr() 将检查当前目录。
os.removexattr(path, attribute, *, follow_symlinks=True)¶
从 path 中删除扩展文件系统属性 attribute。attribute 应该是 bytes 或 str (直接/间接通过 PathLike 接口返回的)。如果是字符串,则它应使用文件系统编码来编码。
3.6 版更變:接受一个 类路径对象 作为 path 和 attribute。
os.setxattr(path, attribute, value, flags=0, *, follow_symlinks=True)¶
将 path 的扩展文件系统属性 attribute 设置为 value。attribute 必须是没有空字符的 bytes 或 str (直接传入或通过 PathLike 接口间接传入)。如果是 str,则应使用文件系统编码进行编码。flags 可以是 XATTR_REPLACE 或 XATTR_CREATE。如果指定 XATTR_REPLACE 而该属性不存在,则抛出 EEXISTS 异常。如果指定 XATTR_CREATE 而该属性已经存在,则不会创建该属性,抛出 ENODATA 异常。
備註
Linux kernel 2.6.39 以下版本的一个 bug 导致在某些文件系统上,flags 参数会被忽略。
3.6 版更變:接受一个 类路径对象 作为 path 和 attribute。
os.XATTR_SIZE_MAX¶
一条扩展属性的值的最大大小。在当前的 Linux 上是 64 KiB。
os.XATTR_CREATE¶
这是 setxattr() 的 flags 参数的可取值,它表示该操作必须创建一个属性。
os.XATTR_REPLACE¶
这是 setxattr() 的 flags 参数的可取值,它表示该操作必须替换现有属性。