Get human readable version of file size?
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
A library that has all the functionality that it seems you're looking for is humanize
. humanize.naturalsize()
seems to do everything you're looking for.
The following works in Python 3.6+, is, in my opinion, the easiest to understand answer on here, and lets you customize the amount of decimal places used.
def human_readable_size(size, decimal_places=2): for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']: if size < 1024.0 or unit == 'PiB': break size /= 1024.0 return f"{size:.{decimal_places}f} {unit}"