Python stat Module

The stat module in Python provides constants and functions for interpreting the results of os.stat(), os.fstat(), and os.lstat() system calls. These calls return file attributes, which the stat module helps to decode.

Table of Contents

  1. Introduction
  2. Key Functions
    • filemode
    • S_ISDIR
    • S_ISCHR
    • S_ISBLK
    • S_ISREG
    • S_ISFIFO
    • S_ISLNK
    • S_ISSOCK
  3. Key Constants
    • File Type Constants
    • File Mode Bits
  4. Examples
    • Basic Usage
    • Checking File Types
    • Converting File Mode to String
  5. Real-World Use Case
  6. Conclusion
  7. References

Introduction

The stat module is used to interpret the results of the os.stat(), os.fstat(), and os.lstat() functions, which provide detailed information about a file. This module defines constants and functions for working with file attributes.

Key Functions

filemode

Converts a file's mode to a string of the form -rwxrwxrwx.

import os
import stat

mode = os.stat('example.txt').st_mode
print(stat.filemode(mode))  # -rw-r--r--

S_ISDIR

Returns True if the mode is from a directory.

mode = os.stat('example_directory').st_mode
print(stat.S_ISDIR(mode))  # True or False

S_ISCHR

Returns True if the mode is from a character device.

mode = os.stat('/dev/tty').st_mode
print(stat.S_ISCHR(mode))  # True or False

S_ISBLK

Returns True if the mode is from a block device.

mode = os.stat('/dev/sda').st_mode
print(stat.S_ISBLK(mode))  # True or False

S_ISREG

Returns True if the mode is from a regular file.

mode = os.stat('example.txt').st_mode
print(stat.S_ISREG(mode))  # True or False

S_ISFIFO

Returns True if the mode is from a FIFO (named pipe).

mode = os.stat('example_fifo').st_mode
print(stat.S_ISFIFO(mode))  # True or False

S_ISLNK

Returns True if the mode is from a symbolic link.

mode = os.lstat('example_symlink').st_mode
print(stat.S_ISLNK(mode))  # True or False

S_ISSOCK

Returns True if the mode is from a socket.

mode = os.stat('/var/run/docker.sock').st_mode
print(stat.S_ISSOCK(mode))  # True or False

Key Constants

File Type Constants

  • stat.S_IFMT(mode): Bitmask for the file type bit fields.
  • stat.S_IFDIR: Directory.
  • stat.S_IFCHR: Character device.
  • stat.S_IFBLK: Block device.
  • stat.S_IFREG: Regular file.
  • stat.S_IFIFO: FIFO (named pipe).
  • stat.S_IFLNK: Symbolic link.
  • stat.S_IFSOCK: Socket.

File Mode Bits

  • stat.S_ISUID: Set user ID on execution.
  • stat.S_ISGID: Set group ID on execution.
  • stat.S_ENFMT: Record locking enforced.
  • stat.S_ISVTX: Save swapped text after use (sticky bit).
  • stat.S_IRWXU: Mask for file owner permissions.
  • stat.S_IRUSR: Owner has read permission.
  • stat.S_IWUSR: Owner has write permission.
  • stat.S_IXUSR: Owner has execute permission.
  • stat.S_IRWXG: Mask for group permissions.
  • stat.S_IRGRP: Group has read permission.
  • stat.S_IWGRP: Group has write permission.
  • stat.S_IXGRP: Group has execute permission.
  • stat.S_IRWXO: Mask for permissions for others (not in group).
  • stat.S_IROTH: Others have read permission.
  • stat.S_IWOTH: Others have write permission.
  • stat.S_IXOTH: Others have execute permission.

Examples

Basic Usage

import os
import stat

# Get file stats
file_stat = os.stat('example.txt')

# Print file mode as integer
print(file_stat.st_mode)  # 33204 (example)

# Print file mode as string
print(stat.filemode(file_stat.st_mode))  # -rw-r--r--

Checking File Types

import os
import stat

file_stat = os.stat('example.txt')

# Check if it's a directory
print(stat.S_ISDIR(file_stat.st_mode))  # False

# Check if it's a regular file
print(stat.S_ISREG(file_stat.st_mode))  # True

Converting File Mode to String

import os
import stat

file_stat = os.stat('example.txt')

# Get file mode as string
file_mode_str = stat.filemode(file_stat.st_mode)
print(f"File mode for 'example.txt': {file_mode_str}")  # -rw-r--r--

Real-World Use Case

Listing Files with Permissions

import os
import stat

def list_files_with_permissions(directory):
    for entry in os.listdir(directory):
        path = os.path.join(directory, entry)
        mode = os.stat(path).st_mode
        file_mode_str = stat.filemode(mode)
        print(f"{file_mode_str} {entry}")

list_files_with_permissions('.')

Conclusion

The stat module in Python provides a convenient way to interpret and work with file attributes. By using this module, you can easily check file types, permissions, and other metadata, making it used for file system manipulation and analysis.

References

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare