Python | os.stat 函數

最近更新時間 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()。這不適用於空鏈接或交接點,否則會拋出異常。
rss_feed