["python","code-snippets","filesize"]
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?
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