Python os.stat() Method
The Python method stat() of OS module performs a stat system call on the given path. It is used to retrieve the status of a file or file descriptor.
On invoking the os.stat(), it returns a stat_result object. This object contains various attributes that represent the status of the specified path.
Syntax
Following is the syntax for os.stat() method −
os.stat(path, *, dir_fd, follow_symlinks)
Parameters
The Python os.stat() method accepts the following parameters −
path − This is the path, whose stat information is required.
dir_fd − It is an optional parameter that is a file descriptor referring to a directory.
follow_symlinks − This parameter specifies a boolean that decides whether to follow symbolic links or not.
Return Value
The Python os.stat() methods returns a stat_result object that contains the below attributes −
st_mode − protection bits.
st_ino − inode number.
st_dev − device.
st_nlink − number of hard links.
st_uid − user id of owner.
st_gid − group id of owner.
st_size − size of file, in bytes.
st_atime − time of most recent access.
st_mtime − time of most recent content modification.
st_ctime − time of most recent metadata change.
Example
The following example shows the usage of stat() method. Here, we are displaying stat information of the given file.
import os, sys
# showing stat information of file
statinfo = os.stat("cwd.py")
print("Information related to the file:")
print (statinfo)
When we run above program, it produces following result −
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)
Example
In this example, we are accessing various information related to a given file using the attributes of stat_result object.
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}")
When we run above program, it produces following result −
File Size: 206 bytes Last Modified: 1713161778.4851234 Last Accessed: 1713161783.2907193