views:

468

answers:

4

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?

+1  A: 

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'
Sridhar Ratnakumar
However, this library is not very customizable. >>> from hurry.filesize import size >>> size(1031053) >>> size(3033053)'2M'I expect it show, for example, '2.4M' or '2423K' .. instead of the blatantly approximated '2M'.
Sridhar Ratnakumar
+3  A: 

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

Sridhar Ratnakumar
that snippet returns None with sizes greater than 1024 TB, right?
fortran
Yep - `print sizeof_fmt(999**99)` shows `None`
dbr
+1  A: 

DiveIntoPython3 also talks about this function.

Sridhar Ratnakumar
+1  A: 
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
Matt Joiner