Python: Converting Bytes to Tb/Gb/Mb/Kb

Just dropping a quick entry here, so I can find it later. Maybe later on I'll elaborate more on some similar stuff.

This is just a quick example I wrote of taking bytes, and converting them to human readable sizes:

def convert_bytes(bytes):
    bytes = float(bytes)
    if bytes >= 1099511627776:
        terabytes = bytes / 1099511627776
        size = '%.2fT' % terabytes
    elif bytes >= 1073741824:
        gigabytes = bytes / 1073741824
        size = '%.2fG' % gigabytes
    elif bytes >= 1048576:
        megabytes = bytes / 1048576
        size = '%.2fM' % megabytes
    elif bytes >= 1024:
        kilobytes = bytes / 1024
        size = '%.2fK' % kilobytes
    else:
        size = '%.2fb' % bytes
    return size



Here is an example of the output:

>>> convert_bytes(9898989898879)
'9.00T'
 
>>> convert_bytes(5129898234)
'4.78G'
 
>>> convert_bytes(12898234)
'12.30M'
 
>>> convert_bytes(989898)
'966.70K'


Hoping somebody finds that useful.