🔍 Code Extractor

function format_file_size_v1

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.

Related Versions

Other versions of this component:

  • format_file_size_v1

    From: /tf/active/vicechatdev/SPFCsync/test_upload_modalities.py | Maturity: N/A

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function format_file_size 93.1% similar

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

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/analyze_replica.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 bytes_to_unicode 43.8% similar

    Converts a bytes object to a Unicode string using UTF-8 encoding, or returns the input unchanged if it's not a bytes object.

    From: /tf/active/vicechatdev/patches/util.py
  • function get_file_info 42.7% similar

    Retrieves file metadata including size in bytes and cryptographic hash for a given file path.

    From: /tf/active/vicechatdev/mailsearch/compare_documents.py
← Back to Browse