def human_readable_size(size, decimal_places=3): for unit in ['B','KiB','MiB','GiB','TiB']: if size < 1024.0: break size /= 1024.0 return f"{size:.{decimal_places}f}{unit}"
Here is what the above code is Doing:
1. We start with the size in bytes.
2. We loop through the units, starting with B, and if the size is less than 1024, we break out of the loop.
3. We divide the size by 1024.
4. We return the size with the unit.