How to Check a File's Size in Python
Checking the size of a file is a common task in programming, often required for validation, resource management, or user feedback. Python's standard library provides several straightforward ways to get a file's size in bytes using the os and pathlib modules.
This guide will demonstrate three methods to retrieve a file's size and will also provide a reusable function to convert the raw byte value into a more human-readable format (e.g., KB, MB, GB).
Method 1: Using os.path.getsize()
The os.path.getsize() function is the most direct and readable way to get the size of a file. It takes a file path as an argument and returns the file's size in bytes as an integer.
Solution:
import os
# Assume 'data.xls' is a file in the same directory.
# You can use a relative or absolute path.
file_path = 'data.xls'
try:
# Get the file size in bytes
file_size_bytes = os.path.getsize(file_path)
print(f"The size of '{file_path}' is: {file_size_bytes} bytes")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
Example Output (assuming a 32.5 KB file):
The size of 'data.xls' is: 33280 bytes
This method is simple, clear, and perfectly suited for when you only need the file size.
Method 2: Using os.stat().st_size
The os.stat() function retrieves a status object containing detailed information about a file or directory, including its size, modification times, and permissions. The file size is available through the .st_size attribute of this object.
Solution:
import os
file_path = 'data.xls'
try:
# Get the status object for the file
stat_result = os.stat(file_path)
# Access the size from the .st_size attribute
file_size_bytes = stat_result.st_size
print(f"The size of '{file_path}' is: {file_size_bytes} bytes")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
Example Output:
The size of 'data.xls' is: 33280 bytes
While this works perfectly, it's slightly less direct than os.path.getsize() if you only need the size. os.stat() is more powerful when you need other file metadata in addition to the size.
Method 3: Using pathlib.Path (Modern Approach)
Introduced in Python 3.4, the pathlib module offers a modern, object-oriented approach to filesystem paths. You can create a Path object and call its .stat() method to get the same status information as os.stat().
This is the recommended approach for new Python code.
Solution:
from pathlib import Path
# Create a Path object for the file
file_path = Path('data.xls')
try:
# Get the file size via the stat() method's st_size attribute
file_size_bytes = file_path.stat().st_size
print(f"The size of '{file_path}' is: {file_size_bytes} bytes")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
Example Output:
The size of 'data.xls' is: 33280 bytes
Bonus: Converting Bytes to a Human-Readable Format
File sizes in bytes are often not very intuitive for users. The function below converts a byte count into a more readable string with units like KB, MB, GB, or TB.
The Helper Function:
def convert_bytes_to_readable(size_bytes):
"""Converts a size in bytes to a human-readable format (KB, MB, GB, etc.)."""
if size_bytes == 0:
return "0 B"
import math
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return f"{s} {size_name[i]}"
# Example usage with os.path.getsize()
import os
file_path = 'data.xls'
try:
file_size_bytes = os.path.getsize(file_path)
readable_size = convert_bytes_to_readable(file_size_bytes)
print(f"Raw size: {file_size_bytes} bytes")
print(f"Readable size: {readable_size}")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
Example Output:
Raw size: 33280 bytes
Readable size: 32.5 KB
Conclusion
Python provides several effective ways to check a file's size. To summarize:
- For simplicity and directness, use
os.path.getsize(). It is easy to read and does exactly one job. - For modern, object-oriented code, the
pathlib.Pathobject is the recommended approach (Path(...).stat().st_size). - If you need other file metadata besides the size, use
os.stat()orPath.stat()and access the attributes you need.
You can combine any of these methods with a helper function to convert the byte count into a user-friendly format for display.