os.stat() Method in Python

Python OS Module provides an interface between Python Code and Operating System, through this interface by using different functions you can make some system calls to push OS to do stuff like Opening a File.

os.stat() method in Python performs stat() system call on the specified path, this method can be used for getting status of specified path.

Code Structure of os.stat() Methods
Syntax : os.stat(path)
Parameter path : String or bytes object representing some valid path
Return Type : This method os.stat() returns instance object stat_result of class os.stat_result which represents status of specified path

Returned Types by os.stat() Method – Table

Return Type NameDescription
st_modeRepresents file type and file mode bits
st_inoRepresents inode number on Unix and file index on windows platform
st_devRepresents identifier of device on which file resides
st_nlinkRepresents number of hard links
st_uidRepresents user identifier of file owner
st_gidRepresents group identifier of file owner
st_sizeRepresents size of file in bytes
st_atimeRepresents time of most recent access
st_mtimeRepresents time of most recent content modification
st_ctimeRepresents time of most recent metadata chnage on Unix and creation on windows Operation System
st_atime_nsSame as st_atime but time is expressed in nanoseconds
st_mtime_nsSame as st_mtime but time is expressed in nanoseconds
st_ctime_nsSame as st_ctime but time is expressed in nanoseconds
st_blocksRepresents number of 512-byte blocks allocated for file
st_rdevRepresents type of device, if its an inode device
st_flagsRepresents user defined flags for file

Using os.stat(path) Function in Python

Let’s create a folder Testing on desktop and then create a file inside it named somefile(May be empty or have some text). Then create a .py file inside Testing folder and put following code into that file.

# importing os module  
import os 
  
# path 
path = '/users/josh/desktop/testing/somefile'    # Instead of josh here put your username
 
# Get the status of 
# the specified path 
status = os.stat(path) 
    
# Print the status 
# of the specified path 
print(status) 
# Output of above code will be
os.stat_result(st_mode=33188, st_ino=21221121, 
st_dev=16777222, st_nlink=1, st_uid=501, st_gid=20, 
st_size=55, st_atime=1615950895, st_mtime=1615950893, st_ctime=1615950894)

You Might Also Like

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts