Selected Reading

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
python_files_io.htm
Advertisements