It's trivially simple, but I thought it might be useful to others.
Jay P.
Well, there's 5 minutes of my life I'll never get back :)
Jay P.
def bytesToHumanReadable(bytes, binary=True, precision=1):
"""Convert bytes to a human-readable size.
Given a size in bytes, this function converts it and uses the
largest
suffix possible that does not result in a size that is less than 1
(i.e. 300 KiB instead of 0.3 MiB). By default use binary
size-prefixes,
and if binary=False then use SI size-prefixes.
"""
if binary:
factor = 1024
suffixes = [
'B', # bytes
'KiB', # kibibytes
'MiB', # mebibytes
'GiB', # gibibytes
'TiB', # tebibytes
'PiB', # pebibytes
'EiB', # exbibytes
'ZiB', # zebibytes
'YiB', # yobibytes
]
else:
factor = 1000
suffixes = [
'B', # bytes
'KB', # kilobytes
'MB', # megabytes
'GB', # gigabytes
'TB', # terabytes
'PB', # petabytes
'EB', # exabytes
'ZB', # zettabytes
'YB', # yottabytes
]
format = '%.*f %s'
# Change to float so we don't lose precision in the division
operation.
size = float(bytes)
for suffix in suffixes:
if size >= factor:
size /= factor
else:
if suffix is suffixes[0]:
# Do not use precision for size in bytes.
precision = 0
return format % (precision, size, suffix)
# We are at the end of the suffix list, anything this big gets put
into
# units of the last suffix in the list.
return format % (precision, size, suffixes[-1])
Some examples:
>>> bytesToHumanReadable(1023)
'1023 B'
>>> bytesToHumanReadable(1024)
'1.0 KiB'
>>> bytesToHumanReadable(3215436)
'3.1 MiB'
>>> bytesToHumanReadable(998436)
'975.0 KiB'
>>> bytesToHumanReadable(163456887454)
'152.2 GiB'
>>> bytesToHumanReadable(163456887454, binary=False)
'163.5 GB'
>>> bytesToHumanReadable(163456887454, binary=False, precision=8)
'163.45688745 GB'
>>> bytesToHumanReadable(16345688745446468445546546)
'13.5 YiB'