當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python os.DirEntry.stat()用法及代碼示例

Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。

os.scandir()os模塊產量的方法os.DirEntry與指定路徑給定目錄中的條目相對應的對象。os.DirEntry對象具有各種屬性和方法,用於公開目錄條目的文件路徑和其他文件屬性。

stat()方法開啟os.DirEntryobject用於獲取條目的os.stat_result對象。


注意: os.DirEntry打算在迭代後使用和丟棄對象,因為對象的屬性和方法將其值緩存起來,而不再重新獲取這些值。自調用os.scandir()方法以來,文件的元數據是否已更改,或者是否經過了很長時間。我們將不會獲得up-to-date信息。

用法: os.DirEntry.stat(*, follow_symlinks = True)

參數:
follow_symlinks:此參數需要一個布爾值。如果條目是符號鏈接,並且follow_symlinks為True,則該方法將在符號鏈接指向的路徑上操作。如果條目是符號鏈接,並且follow_symlinks為False,則該方法將在符號鏈接本身上運行。如果該條目不是符號鏈接,則將忽略follow_symlinks參數。此參數的默認值為True。

返回值:此方法返回條目的os.stat_result對象。以下是os.stat_result對象的屬性:

  • st_mode:表示文件類型和文件模式位(權限)。
  • st_ino:它表示Unix上的inode編號和Windows平台上的文件索引。
  • st_dev:它代表此文件所在設備的標識符。
  • st_nlink:它表示硬鏈接的數量。
  • st_uid:它代表文件所有者的用戶標識符。
  • st_gid:它代表文件所有者的組標識符。
  • st_size:它表示文件的大小(以字節為單位)。
  • st_atime:它表示最近訪問的時間。以秒為單位。
  • st_mtime:它表示最近一次內容修改的時間。以秒為單位。
  • st_ctime:它表示Unix上最近的元數據更改時間以及Windows上的創建時間。以秒為單位。
  • st_atime_ns:與st_atime相同,但是時間以納秒為單位表示為整數。
  • st_mtime_ns:與st_mtime相同,但時間以納秒為單位表示為整數。
  • st_ctime_ns:與st_ctime相同,但時間以納秒為單位表示為整數。
  • st_blocks:代表分配給文件的512字節塊的數量。
  • st_rdev:表示設備類型,如果是inode設備。
  • st_flags:它代表用戶定義的文件標誌。

碼:用於os.DirEntry.stat()方法

# Python program to explain os.DirEntry.stat() method  
  
# importing os module   
import os 
  
# Directory to be scanned 
# Path 
path = "/home / ihritik"
  
# Print status of all 
# files in the above 
# specified path 
  
# Using os.scandir() method 
# scan the specified directory 
# and yield os.DirEntry object 
# for each file and sub-directory 
  
print("Status of all files in path '% s':" % path)  
with os.scandir(path) as itr:
    for entry in itr:
        # Check if the entry 
        # is a file  
        if entry.is_file():
            # Print file status     
            print("Status of % s:" % entry.name) 
            print(entry.stat(), "\n")
輸出:
Status of all files in path '/home/ihritik':
Status of file.txt:
os.stat_result(st_mode=33248, st_ino=801366, st_dev=2056, st_nlink=2, st_uid=1000,
st_gid=1000, st_size=409, st_atime=1566360293, st_mtime=1566287810, 
st_ctime=1566291428)

Status of tree.cpp:
os.stat_result(st_mode=33188, st_ino=801364, st_dev=2056, st_nlink=1, st_uid=1000,
st_gid=1000, st_size=820, st_atime=1565604415, st_mtime=1565604415,
st_ctime=1565604415)

Status of graph.cpp:
os.stat_result(st_mode=33188, st_ino=801237, st_dev=2056, st_nlink=1, st_uid=1000,
st_gid=1000, st_size=1729, st_atime=1561515200, st_mtime=1561515069, 
st_ctime=1561515069)

Status of abc.txt
os.stat_result(st_mode=33434, st_ino=801196, st_dev=2056, st_nlink=1, st_uid=1000,
st_gid=1000, st_size=0, st_atime=1560204341, st_mtime=1560204341, 
st_ctime=1560204349)

參考文獻: https://docs.python.org/3/library/os.html#os.DirEntry.stat



相關用法


注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.DirEntry.stat() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。