pythoncode-snippetsfilesize

Get a human-readable version of a file size


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

>>> human_readable(2048)
'2 kilobytes'

How can I do this?


Solution

  • 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:

    Example:

    >>> sizeof_fmt(168963795964)
    '157.4GiB'
    

    by Fred Cirera