Python stat Module: Complete Guide to Installation and Advanced Usage

Python stat Module

The stat module in Python provides a mechanism to retrieve file statistics similar to the Unix stat command. It gives you insight into the attributes of files, such as their size, modification time, access rights, and more, which can be invaluable for various programming tasks. The stat module is included in Python’s standard library and is compatible with Python 3.x versions.

Module Introduction

The stat module is part of the Python Standard Library, available since Python 3.3. It allows developers to access file metadata through an object returned by functions such as os.stat(), which gives detailed information about a file or file descriptor. The information is provided in a structured way, utilizing predefined constants for easier access to specific attributes.

Application Scenarios

The stat module is widely used in applications that require file management and analysis, such as:

  • File Management Systems: To monitor the size and modification date of files regularly.
  • Backup Solutions: To determine if a file has changed since the last backup based on its modification time.
  • Security Auditing: To check permissions and ownership of files for compliance and security checks.

Installation Instructions

The stat module is included with every standard Python installation. You do not need to install it separately. Just make sure you have Python 3.x installed on your system, and you can start using it right away.

Usage Examples

Example 1: Retrieve Basic File Statistics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os
import stat

# Define the path to the file
file_path = 'example.txt'

# Use os.stat() to get file statistics
file_stats = os.stat(file_path)

# Access file size
file_size = file_stats.st_size # Size of the file in bytes
print(f"File Size: {file_size} bytes") # Output the file size

# Access last modification time
mod_time = file_stats.st_mtime # Last modified time (epoch)
print(f"Last Modified Time: {mod_time}")

This example retrieves the size and last modification time of a file named example.txt.

Example 2: Check File Permissions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import os
import stat

# Define the path to the file
file_path = 'example.txt'

# Use os.stat() to get the file statistics
file_stats = os.stat(file_path)

# Check if the file is readable, writable, and executable
is_readable = bool(file_stats.st_mode & stat.S_IRUSR) # Owner has read permission
is_writable = bool(file_stats.st_mode & stat.S_IWUSR) # Owner has write permission
is_executable = bool(file_stats.st_mode & stat.S_IXUSR) # Owner has execute permission

print(f"Is Readable: {is_readable}") # Output: True or False
print(f"Is Writable: {is_writable}") # Output: True or False
print(f"Is Executable: {is_executable}") # Output: True or False

This example checks if the specified file has read, write, or execute permissions for the owner.

Example 3: Extract Detailed File Information

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import os
import stat
from datetime import datetime

# Define the path to the file
file_path = 'example.txt'

# Use os.stat() to get the file statistics
file_stats = os.stat(file_path)

# Get detailed file information
owner_id = file_stats.st_uid # User ID of the file owner
group_id = file_stats.st_gid # Group ID of the file owner
file_type = stat.filemode(file_stats.st_mode) # Human-readable file type and permissions
access_time = datetime.fromtimestamp(file_stats.st_atime) # Last access time (converted to readable format)

print(f"Owner ID: {owner_id}") # Output the owner ID
print(f"Group ID: {group_id}") # Output the group ID
print(f"File Type and Permissions: {file_type}") # Output file permissions
print(f"Last Access Time: {access_time}") # Output the last access time

In this example, we extract various pieces of information about the file, including the owner and group IDs, file permissions, and the last access time, formatted as a human-readable date.

Strongly recommend you follow my blog EVZS Blog. It includes a complete reference and tutorials on all Python standard libraries, making it easier for you to learn and apply Python effectively. By subscribing, you will gain access to numerous practical examples and detailed explanations that can enhance your programming skills significantly. Don’t miss the opportunity to enrich your Python knowledge and keep up with the latest in Python development!

SOFTWARE VERSION MAY CHANG

If this document is no longer applicable or incorrect, please leave a message or contact me for update. Let's create a good learning atmosphere together. Thank you for your support! - Travis Tang