How to Interpret os.stat in Python with stat

When inspecting files in Python, os.stat() returns an os.stat_result object containing low-level numeric metadata such as file sizes, timestamps, and protection modes. Because values like st_mode encode both file type and permission bits into a single raw integer, they can be difficult to parse directly. The standard library's stat module solves this by providing specialized functions, bitmasks, and constants designed to decode, evaluate, and translate these raw numeric attributes into human-readable information and actionable programmatic checks.

File Type Identification Functions

The st_mode attribute contains the file type encoded alongside permission flags. The stat module provides a suite of boolean functions that accept st_mode as an argument to determine the exact type of a filesystem node:

Permission Masks and Decoding

File permissions are stored as bit patterns within st_mode. The stat module defines constants that represent standard POSIX permission flags, enabling bitwise operations to check specific access rights:

To isolate just the permission portion of st_mode, the stat.S_IMODE() function masks out the file type data, leaving only the permissions and special execution bits.

Human-Readable Formatting with filemode

Instead of manually checking individual bitmasks, you can convert the entire st_mode integer into a traditional Unix-style permission string (such as -rw-r--r-- or drwxr-xr-x) using stat.filemode():

import os
import stat

info = os.stat("example.txt")
mode_string = stat.filemode(info.st_mode)
print(mode_string)  # Outputs: -rw-r--r--

Practical Application

Here is how to combine os.stat() and stat to interpret metadata:

import os
import stat

path = "example.txt"
file_stat = os.stat(path)

# Determine the file type
if stat.S_ISDIR(file_stat.st_mode):
    file_type = "Directory"
elif stat.S_ISREG(file_stat.st_mode):
    file_type = "Regular File"
else:
    file_type = "Other"

# Check specific permissions
has_user_write = bool(file_stat.st_mode & stat.S_IWUSR)
octal_permissions = oct(stat.S_IMODE(file_stat.st_mode))

print(f"Type: {file_type}")
print(f"User Write Allowed: {has_user_write}")
print(f"Octal Mode: {octal_permissions}")
print(f"Format String: {stat.filemode(file_stat.st_mode)}")

Index Constants for Legacy Tuple Unpacking

While modern Python allows accessing attributes via names like file_stat.st_size, os.stat_result objects can also be accessed as standard tuples. The stat module defines integer index constants—such as stat.ST_MODE, stat.ST_INO, stat.ST_DEV, stat.ST_UID, and stat.ST_SIZE—to support index-based access across legacy implementations.