There are various snippets on the web that would give you a function to return human readable size from bytes size:
>>> human_readable(2048)
'2 bytes'
>>>
But is there a Python library that provides this?
There are various snippets on the web that would give you a function to return human readable size from bytes size:
>>> human_readable(2048)
'2 bytes'
>>>
But is there a Python library that provides this?
One such library is hurry.filesize.
>>> from hurry.filesize import alternative
>>> size(1, system=alternative)
'1 byte'
>>> size(10, system=alternative)
'10 bytes'
>>> size(1024, system=alternative)
'1 KB'
Addressing the above mentioned problem with hurry.filesize
:
def sizeof_fmt(num):
for x in ['bytes','KB','MB','GB','TB']:
if num < 1024.0:
return "%3.1f%s" % (num, x)
num /= 1024.0
Example:
>>> sizeof_fmt(168963795964)
'157.4GB'
by Fred Cirera
def human_readable_data_quantity(quantity, multiple=1024):
if quantity == 0:
quantity = +0
SUFFIXES = ["B"] + [i + {1000: "B", 1024: "iB"}[multiple] for i in "KMGTPEZY"]
for suffix in SUFFIXES:
if quantity < multiple or suffix == SUFFIXES[-1]:
if suffix == SUFFIXES[0]:
return "%d%s" % (quantity, suffix)
else:
return "%.1f%s" % (quantity, suffix)
else:
quantity /= multiple