Stat() Function Of Os Module In Python

Function:

os.stat(path, *, dir_fd=None, follow_symlinks=True)

Overview:

  • The function os.stat() returns information about a file returned as a os.stat_result object. The attributes of the os.stat_result and their meanings are given below:

Attribute

Description

st_mode

Type and mode of the file.

st_ino

The index count of the inode that holds the information on the file. In Unix like operating systems, an inode is a data structure that holds storage block location and other attributes of the file. 

st_dev

Name of the device where the file is present. Using the function os.major() and os.minor(), major and minor device numbers can be found. 

st_nlink

Number of hard links to the file.

st_uid

User id.

st_gid

Group id.

st_size

Size of the file in bytes.

st_atime

Time the file was accessed last.

st_mtime

Time the file was modified last.

st_ctime

Time of the last status change of the file.

Parameters:

path - File path for which information is needed.   

dir_fd - Optional parameter. If provided the path is considered relative to the directory as represented by the descriptor.

follow_symlinks - Optional parameter. If the path points to a symbolic link, the follow_symlinks flag resolves with the link itself or to the actual file pointed to.

Return Value:

An object of type os.stat_result.

Example:

# Example Python program that provides information about a file using the
# function os.stat()
import os

# File path
path = "/ex/Wheels.txt"

# Get file information
stats = os.stat(path)

# Print file information
print("Statistics for the file %s:"%path)
print("===Mode===")
print("File type and mode:%o"%stats.st_mode)

print("===Storage related:===")
print("Inode number:%d"%stats.st_ino)

deviceNum      =  stats.st_dev
majorDeviceNum =  os.major(deviceNum)
minorDeviceNum =  os.minor(deviceNum)

print("Device id:%d"%deviceNum)
print("Major device number:%d"%majorDeviceNum)
print("Minor device number:%d"%minorDeviceNum)
 
print("File Size in bytes:%d"%stats.st_size)
print("Number of hard links to the file:%d"%stats.st_nlink)

print("===User & Group:===")
print("User Id of the file owner:%d"%stats.st_uid)
print("Group id of the file owner:%d"%stats.st_gid)

print("===Time Related:===")
print("Time last accessed:%d"%stats.st_atime)
print("Time last modified:%d"%stats.st_mtime)
print("Time of last status change:%d"%stats.st_ctime)
print(type(stats))

 

Output:

Statistics for the file /ex/Wheels.txt:
===Mode===
File type and mode:100644
===Storage related:===
Inode number:7657914
Device id:16777220
Major device number:1
Minor device number:4
File Size in bytes:40
Number of hard links to the file:1
===User & Group:===
User Id of the file owner:501
Group id of the file owner:0
===Time Related:===
Time last accessed:1683042584
Time last modified:1683040824
Time of last status change:1683040824
<class 'os.stat_result'>

 


Copyright 2023 © pythontic.com