Python os.stat() 方法



Python 的 `os.stat()` 方法對給定的路徑執行 stat 系統呼叫。它用於檢索檔案或檔案描述符的狀態。

呼叫 `os.stat()` 時,它返回一個 `stat_result` 物件。此物件包含表示指定路徑狀態的各種屬性。

語法

以下是 os.stat() 方法的語法:

os.stat(path, *, dir_fd, follow_symlinks)

引數

Python 的 os.stat() 方法接受以下引數:

  • path − 這是需要獲取其 stat 資訊的路徑。

  • dir_fd − 這是一個可選引數,是一個指向目錄的檔案描述符。

  • follow_symlinks − 此引數指定一個布林值,決定是否跟隨符號連結。

返回值

Python 的 os.stat() 方法返回一個包含以下屬性的 `stat_result` 物件:

  • st_mode − 保護位。

  • st_ino − i 節點號。

  • st_dev − 裝置。

  • st_nlink − 硬連結數。

  • st_uid − 所有者的使用者 ID。

  • st_gid − 所有者的組 ID。

  • st_size − 檔案大小(以位元組為單位)。

  • st_atime − 最近訪問時間。

  • st_mtime − 最近內容修改時間。

  • st_ctime − 最近元資料更改時間。

示例

以下示例演示了 `stat()` 方法的使用。在這裡,我們顯示給定檔案的 stat 資訊。

import os, sys

# showing stat information of file
statinfo = os.stat("cwd.py")
print("Information related to the file:")
print (statinfo)

執行上述程式時,它會產生以下結果:

Information related to the file:
os.stat_result(st_mode=33204, st_ino=1055023, st_dev=2051, 
st_nlink=1, st_uid=1000, st_gid=1000, st_size=206, st_atime=1713161783, 
st_mtime=1713161778, st_ctime=1713161778)

示例

在這個例子中,我們使用 `stat_result` 物件的屬性訪問與給定檔案相關的各種資訊。

import os

# Retrieve the info of the file
statinfo = os.stat("cwd.py")

# displaying the info
print(f"File Size: {statinfo.st_size} bytes")
print(f"Last Modified: {statinfo.st_mtime}")
print(f"Last Accessed: {statinfo.st_atime}")

執行上述程式時,它會產生以下結果:

File Size: 206 bytes
Last Modified: 1713161778.4851234
Last Accessed: 1713161783.2907193
python_files_io.htm
廣告
© . All rights reserved.