🔍 Code Extractor

function format_file_size

Maturity: 42

Converts a file size in bytes to a human-readable string format with appropriate units (B, KB, MB, GB, TB).

File:
/tf/active/vicechatdev/SPFCsync/dry_run_test.py
Lines:
19 - 28
Complexity:
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.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function format_file_size_v1 97.9% similar

    Converts a file size in bytes to a human-readable string format with appropriate units (B, KB, MB, GB, TB).

    From: /tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
  • function human_readable_size 81.0% similar

    Converts a byte size value into a human-readable string format with appropriate unit suffixes (B, KB, MB, GB, TB).

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function format_datetime_v1 42.1% similar

    Converts an ISO format datetime string into a human-readable UTC datetime string formatted as 'YYYY-MM-DD HH:MM:SS UTC'.

    From: /tf/active/vicechatdev/SPFCsync/dry_run_test.py
  • function format_date 38.8% similar

    Formats a datetime object into a string representation according to a predefined DATE_FORMAT constant, returning an empty string if the input is None.

    From: /tf/active/vicechatdev/CDocs/utils/__init__.py
  • function test_us_with_thousands 37.9% similar

    A unit test function that validates the smart_read_csv function's ability to correctly parse US-formatted CSV files containing numbers with thousand separators (commas) and decimal points.

    From: /tf/active/vicechatdev/vice_ai/test_regional_formats.py
← Back to Browse