Reusable library to get human readable version of file size?

Sridhar Ratnakumar picture Sridhar Ratnakumar · Jul 7, 2009 · Viewed 104.6k times · Source

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 kilobytes'
>>>

But is there a Python library that provides this?

Answer

Sridhar Ratnakumar picture Sridhar Ratnakumar · Jul 7, 2009

Addressing the above "too small a task to require a library" issue by a straightforward implementation:

def sizeof_fmt(num, suffix='B'):
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

Supports:

  • all currently known binary prefixes
  • negative and positive numbers
  • numbers larger than 1000 Yobibytes
  • arbitrary units (maybe you like to count in Gibibits!)

Example:

>>> sizeof_fmt(168963795964)
'157.4GiB'

by Fred Cirera