Python | os.stat 函数
Lasted 2020-12-09 11:54:13
os.stat 函数获取文件或文件描述符的状态。在所给路径上执行等效于 stat() 系统调用的操作。path 可以是字符串类型,或(直接传入或通过 PathLike 接口间接传入的) bytes 类型,或打开的文件描述符。返回一个 stat_result 对象。
本函数默认会跟踪符号链接,要获取符号链接本身的 stat,请添加 follow_symlinks=False 参数,或使用 lstat()。
函数定义
os.stat(path, *, dir_fd=None, follow_symlinks=True)
# 函数定义
def stat(path: _FdOrPathType, *, dir_fd: Optional[int] = ..., follow_symlinks: bool = ...) -> stat_result: ...
# 返回值 os.stat_result 定义
class stat_result:
st_mode: int # protection bits,
st_ino: int # inode number,
st_dev: int # device,
st_nlink: int # number of hard links,
st_uid: int # user id of owner,
st_gid: int # group id of owner,
st_size: int # size of file, in bytes,
st_atime: float # time of most recent access,
st_mtime: float # time of most recent content modification,
st_ctime: float # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows)
st_atime_ns: int # time of most recent access, in nanoseconds
st_mtime_ns: int # time of most recent content modification in nanoseconds
st_ctime_ns: int # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds
if sys.version_info >= (3, 8) and sys.platform == "win32":
st_reparse_tag: int
def __getitem__(self, i: int) -> int: ...
# not documented
def __init__(self, tuple: Tuple[int, ...]) -> None: ...
# On some Unix systems (such as Linux), the following attributes may also
# be available:
st_blocks: int # number of blocks allocated for file
st_blksize: int # filesystem blocksize
st_rdev: int # type of device if an inode device
st_flags: int # user defined flags for file
# On other Unix systems (such as FreeBSD), the following attributes may be
# available (but may be only filled out if root tries to use them):
st_gen: int # file generation number
st_birthtime: int # time of file creation
# On Mac OS systems, the following attributes may also be available:
st_rsize: int
st_creator: int
st_type: int
参数
- checkpath - 目录或文件路径。
返回值
- checkstat_result - 返回值参见函数定义。
示例1: - 使用 os.stat() 函数返回文件或文件描述符的状态,获取文件大小。
# coding=utf-8
# Python3 代码
# 讲解怎样使用 os.stat() 函数返回文件或文件描述符的状态
# 引入 os 库
import os
# 文件路径
path = "foo.txt"
# 获取文件状态
stat_info = os.stat(path)
# 打印文件状态图
print(stat_info)
# 打印文件大小
print("Size of file::", stat_info.st_size)
os.stat_result(st_mode=33188, st_ino=12349, st_dev=2064, st_nlink=1, st_uid=0, st_gid=0, st_size=9, st_atime=1607401483, st_mtime=1607401517, st_ctime=1607401517) Size of file:: 9
在 Windows 上,传入 follow_symlinks=False 将禁用所有名称代理重解析点,其中包括符号链接和目录结点。其他类型的重解析点将直接打开,比如不像链接的或系统无法跟踪的重解析点。当多个链接形成一个链时,本方法可能会返回原始链接的 stat,无法完整遍历到非链接的对象。在这种情况下,要获取最终路径的 stat,请使用 os.path.realpath() 函数尽可能地解析路径,并在解析结果上调用 lstat()。这不适用于空链接或交接点,否则会抛出异常。