🔍 Code Extractor

function format_file_size_v1

Maturity: 40

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/test_upload_modalities.py
Lines:
16 - 25
Complexity:
simple

Purpose

This utility function takes a file size in bytes and formats it into a more readable representation by automatically selecting the most appropriate unit (bytes, kilobytes, megabytes, gigabytes, or terabytes). It handles None values gracefully by returning 'Unknown' and formats numbers to one decimal place for clarity. Commonly used in file management systems, download managers, or any application that needs to display file sizes to users.

Source Code

def format_file_size(size_bytes):
    """Format file size in 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 potentially confusing 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 B', '2.3 GB', 'Unknown'.

Usage Example

# Basic usage examples
size1 = format_file_size(1024)
print(size1)  # Output: '1.0 KB'

size2 = format_file_size(1536)
print(size2)  # Output: '1.5 KB'

size3 = format_file_size(1048576)
print(size3)  # Output: '1.0 MB'

size4 = format_file_size(None)
print(size4)  # Output: 'Unknown'

size5 = format_file_size(500)
print(size5)  # Output: '500.0 B'

size6 = format_file_size(5368709120)
print(size6)  # Output: '5.0 GB'

Best Practices

  • This function assumes 1 KB = 1024 bytes (binary units) rather than 1000 bytes (decimal units). Be aware of this when displaying sizes that need to match system conventions.
  • The function does not validate that size_bytes is non-negative. Consider adding validation if negative values are not expected in your use case.
  • The function stops at TB (terabytes). Files larger than 1024 TB will still be displayed in TB units, which may result in very large numbers.
  • The function returns a string, not a numeric value, so it cannot be used for mathematical operations after formatting.
  • For consistency in user interfaces, always use this function for all file size displays rather than mixing formatted and unformatted sizes.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function format_file_size 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/dry_run_test.py
  • function human_readable_size 80.3% 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.8% 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 37.7% 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 36.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