Python os.fstat() 方法



Python 的fstat()方法返回有關與檔案描述符關聯的檔案的資訊。檔案描述符是當前由程序開啟的檔案的唯一識別符號。以下是 fstat 方法返回的資訊:

  • st_dev - 包含檔案的裝置ID

  • st_ino - inode 號碼

  • st_mode - 保護模式

  • st_nlink - 硬連結數

  • st_uid - 所有者的使用者ID

  • st_gid - 所有者的組ID

  • st_rdev - 裝置ID(如果為特殊檔案)

  • st_size - 總大小(以位元組為單位)

  • st_blksize - 檔案系統I/O的塊大小

  • st_blocks - 已分配的塊數

  • st_atime - 最後訪問時間

  • st_mtime - 最後修改時間

  • st_ctime - 最後狀態更改時間

os.fstat() 方法的工作方式類似於 "os.stat()" 方法,但在您擁有檔案描述符而不是檔案路徑時使用。

語法

fstat() 方法的語法如下:

os.fstat(fd)

引數

Python 的os.fstat()方法接受單個引數:

  • fd - 這是要返回系統資訊的資料夾描述符。

返回值

Python 的os.fstat()方法返回有關與檔案描述符關聯的檔案的資訊。

示例

以下示例顯示了 fstat() 方法的用法。結果將包含一個包含有關檔案資訊的 "stat_result" 物件。

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Now get the touple
info = os.fstat(fd)
print ("Printing the Info of File :", info)

# Close opened file
os.close( fd)

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

Printing the Info of File : os.stat_result(st_mode=33277, st_ino=1054984, st_dev=2051, st_nlink=1, st_uid=1000, st_gid=1000, st_size=0, st_atime=1713157516, st_mtime=1713157516, st_ctime=1713157517)

示例

在下面的示例中,我們使用 fstat() 方法顯示給定檔案的 UID 和 GID。

#!/usr/bin/python
import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )
info = os.fstat(fd)

# Now get uid of the file
print ("UID of the file :%d" % info.st_uid)

# Now get gid of the file
print ("GID of the file :%d" % info.st_gid)

# Close opened file
os.close( fd)
print("File closed successfully!!")

執行上述程式後,將顯示以下結果:

UID of the file :1000
GID of the file :1000
File closed successfully!!
python_files_io.htm
廣告