Python libraries to calculate human readable filesize from bytes?

pynovice picture pynovice · Feb 21, 2013 · Viewed 16.1k times · Source

I find hurry.filesize very useful but it doesn't give output in decimal?

For example:

print size(4026, system=alternative) gives 3 KB.

But later when I add all the values I don't get the exact sum. For example if the output of hurry.filesize is in 4 variable and each value is 3. If I add them all, I get output as 15.

I am looking for alternative of hurry.filesize to get output in decimals too.

Answer

nneonneo picture nneonneo · Feb 21, 2013

This isn't really hard to implement yourself:

suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
def humansize(nbytes):
    i = 0
    while nbytes >= 1024 and i < len(suffixes)-1:
        nbytes /= 1024.
        i += 1
    f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
    return '%s %s' % (f, suffixes[i])

Examples:

>>> humansize(131)
'131 B'
>>> humansize(1049)
'1.02 KB'
>>> humansize(58812)
'57.43 KB'
>>> humansize(68819826)
'65.63 MB'
>>> humansize(39756861649)
'37.03 GB'
>>> humansize(18754875155724)
'17.06 TB'