How to Check File Size in Python
Knowing the size of a file is a common requirement in Python programming, whether you're validating uploads, monitoring disk usage, logging file statistics, or deciding how to process large datasets. Python provides several built-in ways to check file size without needing any third-party libraries.
In this guide, you'll learn how to check file size in Python using the pathlib module, the os module, and the os.stat() function. Each method includes examples with outputs and practical tips for real-world usage.
Using pathlib.Path.stat()
The pathlib module, available since Python 3.4, offers a modern and object-oriented approach to file system operations. The Path.stat().st_size attribute returns the file size in bytes.
from pathlib import Path
file_path = Path('Data.csv')
size_in_bytes = file_path.stat().st_size
print(f"File size: {size_in_bytes} bytes")
Output:
File size: 226 bytes
pathlib is the recommended approach for new Python projects. It provides clean, readable syntax and works consistently across operating systems.
Using os.path.getsize()
The os.path.getsize() function is a straightforward way to get the size of a file. It accepts a file path as a string and returns the size in bytes.
import os
size_in_bytes = os.path.getsize("Data.csv")
print(f"File size: {size_in_bytes} bytes")
Output:
File size: 226 bytes
This method is concise and widely used, especially in codebases that already rely on the os module.
Using os.stat()
The os.stat() function returns a stat result object containing multiple file attributes. The st_size attribute gives the file size in bytes, similar to the pathlib approach but using the os module.
import os
file_stats = os.stat("Data.csv")
size_in_bytes = file_stats.st_size
print(f"File size: {size_in_bytes} bytes")
Output:
File size: 226 bytes
os.stat() is particularly useful when you need additional file metadata alongside the size, such as modification time or permissions:
import os
import time
file_stats = os.stat("Data.csv")
print(f"Size: {file_stats.st_size} bytes")
print(f"Last modified: {time.ctime(file_stats.st_mtime)}")
print(f"Created: {time.ctime(file_stats.st_ctime)}")
Output:
Size: 226 bytes
Last modified: Wed Jul 23 10:30:15 2025
Created: Mon Jul 21 08:12:45 2025
Converting Bytes to Human-Readable Formats
All three methods return the file size in bytes. For larger files, raw byte values are hard to read. Here's a utility function to convert bytes into a human-friendly format:
def format_file_size(size_in_bytes):
"""Convert bytes to a human-readable string."""
for unit in ['bytes', 'KB', 'MB', 'GB', 'TB']:
if size_in_bytes < 1024:
return f"{size_in_bytes:.2f} {unit}"
size_in_bytes /= 1024
return f"{size_in_bytes:.2f} PB"
# Example usage
import os
size = os.path.getsize("Data.csv")
print(format_file_size(size))
# Test with larger values
print(format_file_size(1048576)) # 1 MB
print(format_file_size(1073741824)) # 1 GB
Output:
226.00 bytes
1.00 MB
1.00 GB
Handling Errors Gracefully
If the file doesn't exist, all three methods raise an error:
import os
size = os.path.getsize("nonexistent_file.txt")
Output:
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'
Always check if the file exists first or wrap the call in a try/except block:
import os
file_path = "nonexistent_file.txt"
# Approach 1: Check before accessing
if os.path.exists(file_path):
size = os.path.getsize(file_path)
print(f"File size: {size} bytes")
else:
print(f"File '{file_path}' not found.")
Output:
File 'nonexistent_file.txt' not found.
# Approach 2: Use try/except
try:
size = os.path.getsize(file_path)
print(f"File size: {size} bytes")
except FileNotFoundError:
print(f"File '{file_path}' not found.")
Output:
File 'nonexistent_file.txt' not found.
Checking the Size of Multiple Files
You can combine these methods with directory listing to check sizes of all files in a folder:
from pathlib import Path
folder = Path('.')
for file in sorted(folder.iterdir()):
if file.is_file():
size = file.stat().st_size
print(f"{file.name:30s} {size:>10,} bytes")
Output:
Data.csv 226 bytes
main.py 1,482 bytes
requirements.txt 58 bytes
Quick Comparison of Methods
| Method | Module | Returns | Best For |
|---|---|---|---|
Path.stat().st_size | pathlib | Size in bytes | Modern, object-oriented code |
os.path.getsize() | os | Size in bytes | Quick, simple file size checks |
os.stat().st_size | os | Size in bytes + metadata | When you need multiple file attributes |
Conclusion
Python makes checking file size simple with three built-in approaches:
pathlib.Path.stat().st_size: the modern, Pythonic choice recommended for new projects.os.path.getsize(): a clean one-liner ideal for quick checks.os.stat().st_size: the best option when you need file size alongside other metadata like modification time.
All three return the size in bytes, so use a conversion function for human-readable output with larger files. Whichever method you choose, always handle the possibility of missing files with proper error checking to keep your code robust.