function format_file_size
Converts a file size in bytes to a human-readable string format with appropriate units (B, KB, MB, GB, TB).
/tf/active/vicechatdev/SPFCsync/dry_run_test.py
19 - 28
simple
Purpose
This utility function formats raw byte values into user-friendly file size representations by automatically selecting the most appropriate unit (bytes, kilobytes, megabytes, gigabytes, or terabytes) and formatting the output to one decimal place. It handles None values gracefully by returning 'Unknown'. Commonly used in file management systems, storage displays, and data transfer interfaces where file sizes need to be presented to end users.
Source Code
def format_file_size(size_bytes):
"""Convert bytes to human readable format"""
if size_bytes is None:
return "Unknown"
for unit in ['B', 'KB', 'MB', 'GB']:
if size_bytes < 1024.0:
return f"{size_bytes:.1f} {unit}"
size_bytes /= 1024.0
return f"{size_bytes:.1f} TB"
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
size_bytes |
- | - | positional_or_keyword |
Parameter Details
size_bytes: The file size in bytes as a numeric value (int or float). Can be None, in which case the function returns 'Unknown'. Expected to be non-negative for meaningful results, though negative values will be processed (resulting in negative formatted output).
Return Value
Returns a string representing the formatted file size. Format is '{value:.1f} {unit}' where value is rounded to one decimal place and unit is one of 'B', 'KB', 'MB', 'GB', or 'TB'. Returns 'Unknown' if size_bytes is None. Examples: '1.5 KB', '250.0 MB', '1.2 GB', 'Unknown'.
Usage Example
# Basic usage examples
size1 = format_file_size(1024)
print(size1) # Output: '1.0 KB'
size2 = format_file_size(1536000)
print(size2) # Output: '1.5 MB'
size3 = format_file_size(5368709120)
print(size3) # Output: '5.0 GB'
size4 = format_file_size(None)
print(size4) # Output: 'Unknown'
size5 = format_file_size(500)
print(size5) # Output: '500.0 B'
# Use in file listing context
import os
file_path = 'example.txt'
if os.path.exists(file_path):
file_size = os.path.getsize(file_path)
readable_size = format_file_size(file_size)
print(f'{file_path}: {readable_size}')
Best Practices
- This function uses 1024 as the conversion factor (binary units), which is standard for file systems. Be aware that some contexts use 1000 (decimal units) instead.
- The function does not validate that size_bytes is non-negative. Consider adding validation if negative values should be rejected.
- The function stops at TB (terabytes). For extremely large values (petabytes and beyond), it will still display in TB units.
- The output is always formatted to one decimal place, which provides a good balance between precision and readability for most use cases.
- When size_bytes is exactly 0, the function returns '0.0 B', which is correct and expected behavior.
- This function is purely for display purposes and should not be used for calculations or comparisons of file sizes.
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function format_file_size_v1 97.9% similar
-
function human_readable_size 81.0% similar
-
function format_datetime_v1 42.1% similar
-
function format_date 38.8% similar
-
function test_us_with_thousands 37.9% similar