Convert Storage Sizes using Python

The following are two Python scripts that will allow you to convert storage sizes. Example usage of the above script: The next script will allow an end user to set the value, source unit and the destination unit:

Convert Storage Sizes using Python
Photo by benjamin lehman / Unsplash

The following are two Python scripts that will allow you to convert storage sizes.

def convert_size(size_bytes, unit=None):
    """
    Convert the given size in bytes to a human-readable format.

    :param size_bytes: The size to convert, in bytes.
    :param unit: The desired unit to convert to (optional).
    :return: The converted size and unit, as a string.
    """
    units = ['bytes', 'KB', 'MB', 'GB', 'TB']
    if unit and unit not in units:
        raise ValueError(f'Invalid unit: {unit}.')
    if size_bytes < 0:
        raise ValueError('Size must be non-negative.')
    if size_bytes == 0:
        return '0 bytes'

    if unit is None:
        # Determine the appropriate unit based on the size.
        unit_idx = 0
        while size_bytes >= 1024 and unit_idx < len(units) - 1:
            size_bytes /= 1024
            unit_idx += 1
        unit = units[unit_idx]
    else:
        # Convert to the desired unit.
        unit_idx = units.index(unit)
        size_bytes /= 1024 ** unit_idx

    return f'{size_bytes:.2f} {unit}'

Example usage of the above script:

print(convert_size(1024))  # Output: "1.00 KB"
print(convert_size(123456789))  # Output: "117.74 MB"
print(convert_size(123456789, 'GB'))  # Output: "0.12 GB"

The next script will allow an end user to set the value, source unit and the destination unit:

def convert_size(size, src_unit, dst_unit):
    """
    Convert the given size from the source unit to the destination unit.

    :param size: The size to convert.
    :param src_unit: The source unit of the size.
    :param dst_unit: The destination unit to convert to.
    :return: The converted size.
    """
    units = {
        'bytes': 1,
        'KB': 1024,
        'MB': 1024 ** 2,
        'GB': 1024 ** 3,
        'TB': 1024 ** 4
    }
    if src_unit not in units:
        raise ValueError(f'Invalid source unit: {src_unit}.')
    if dst_unit not in units:
        raise ValueError(f'Invalid destination unit: {dst_unit}.')
    if size < 0:
        raise ValueError('Size must be non-negative.')

    src_bytes = size * units[src_unit]
    dst_bytes = src_bytes / units[dst_unit]

    return dst_bytes


# Get user input for the size and units.
size = float(input('Enter the size: '))
src_unit = input('Enter the source unit: ')
dst_unit = input('Enter the destination unit: ')

# Call the conversion function and print the result.
converted = convert_size(size, src_unit, dst_unit)
print(f'{size} {src_unit} is {converted:.2f} {dst_unit}.')