Alex Rivera | Logout

Get a human-readable version of a file size

Asked 2009-07-07T20:59:32.397
372

A function to return a human-readable size from the bytes size:

>>> human_readable(2048)
'2 kilobytes'

How can I do this?

Edit
Report

1 Answer

813

Addressing the above "too small a task to require a library" issue by a straightforward implementation (using f-strings, so Python 3.6+):

def sizeof_fmt(num, suffix="B"):
    for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
        if abs(num) < 1024.0:
            return f"{num:3.1f}{unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f}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

answered 2009-07-07T21:15:41.397

Your Answer