Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to get stat of a file using Python?
Getting file statistics is essential for file processing and manipulation in Python. The os module provides built-in functions to retrieve file metadata like size, permissions, timestamps, and more.
Using os.stat() for Basic File Stats
The os.stat() function returns a named tuple containing various file statistics −
import os
# Create a sample file for demonstration
with open('sample.txt', 'w') as f:
f.write("Hello, World!")
# Get the file stats
file_stats = os.stat('sample.txt')
# Access individual stats
file_size = file_stats.st_size
last_modified = file_stats.st_mtime
creation_time = file_stats.st_ctime
# Print the file stats
print("File Size:", file_size, "bytes")
print("Last Modified:", last_modified)
print("Creation Time:", creation_time)
File Size: 13 bytes Last Modified: 1689518818.7932744 Creation Time: 1689518818.7932744
Converting Timestamps to Readable Format
Timestamps are returned as Unix timestamps. Convert them to human-readable format using the datetime module −
import os
from datetime import datetime
# Create a sample file
with open('sample.txt', 'w') as f:
f.write("Hello, World!")
# Get the file stats
file_stats = os.stat('sample.txt')
# Access the last modified timestamp
last_modified = file_stats.st_mtime
# Convert the timestamp to a readable format
last_modified_str = datetime.fromtimestamp(last_modified).strftime("%Y-%m-%d %H:%M:%S")
# Print the formatted timestamp
print("Last Modified:", last_modified_str)
Last Modified: 2023-07-16 14:47:07
Checking File Accessibility
Use os.access() to check if a file can be read, written to, or executed −
import os
# Create a sample file
with open('sample.txt', 'w') as f:
f.write("Hello, World!")
# Check file accessibility
is_readable = os.access('sample.txt', os.R_OK)
is_writable = os.access('sample.txt', os.W_OK)
is_executable = os.access('sample.txt', os.X_OK)
# Print the results
print("Read Access:", is_readable)
print("Write Access:", is_writable)
print("Execute Access:", is_executable)
Read Access: True Write Access: True Execute Access: False
Checking if a File Exists
Use os.path.exists() to verify if a file exists at a given path −
import os
# Check if the file exists
file_exists = os.path.exists('sample.txt')
# Print the result
if file_exists:
print("File exists!")
else:
print("File does not exist.")
File exists!
Getting File Extension
Extract the file extension using os.path.splitext() −
import os
# Create a sample file
file_path = 'sample.txt'
# Get the file extension
file_type = os.path.splitext(file_path)[1]
# Print the file type
print("File Extension:", file_type)
File Extension: .txt
Getting File Permissions
Retrieve file permissions using os.stat() with bitwise operations −
import os
import stat
# Create a sample file
with open('sample.txt', 'w') as f:
f.write("Hello, World!")
# Get the file permissions
file_mode = os.stat('sample.txt').st_mode
file_permissions = oct(file_mode & stat.S_IRWXU)
# Print the file permissions
print("File Permissions:", file_permissions)
File Permissions: 0o600
Complete File Stats Example
Here's a comprehensive example that demonstrates retrieving multiple file statistics −
import os
import stat
from datetime import datetime
# Create a sample file
filename = 'complete_example.txt'
with open(filename, 'w') as f:
f.write("This is a complete example file.")
# Get all file stats
file_stats = os.stat(filename)
print("=== File Statistics ===")
print(f"File: {filename}")
print(f"Size: {file_stats.st_size} bytes")
print(f"Mode: {oct(file_stats.st_mode)}")
print(f"UID: {file_stats.st_uid}")
print(f"GID: {file_stats.st_gid}")
print(f"Access Time: {datetime.fromtimestamp(file_stats.st_atime)}")
print(f"Modify Time: {datetime.fromtimestamp(file_stats.st_mtime)}")
print(f"Change Time: {datetime.fromtimestamp(file_stats.st_ctime)}")
# Check permissions
print("\n=== Permissions ===")
print(f"Readable: {os.access(filename, os.R_OK)}")
print(f"Writable: {os.access(filename, os.W_OK)}")
print(f"Executable: {os.access(filename, os.X_OK)}")
# Clean up
os.remove(filename)
=== File Statistics === File: complete_example.txt Size: 33 bytes Mode: 0o100644 UID: 1000 GID: 1000 Access Time: 2023-07-16 14:47:07.123456 Modify Time: 2023-07-16 14:47:07.123456 Change Time: 2023-07-16 14:47:07.123456 === Permissions === Readable: True Writable: True Executable: False
Conclusion
Python's os module provides powerful functions like os.stat() and os.access() for retrieving file statistics. Use these tools to check file permissions, sizes, timestamps, and existence before performing file operations.
