Last active
February 17, 2025 14:47
-
-
Save lboulard/a93cf2020188b7fcdcc06ade90313a78 to your computer and use it in GitHub Desktop.
Pretty size defined in bytes #python #beautify
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Based on this (incorrect) response <https://stackoverflow.com/a/43750422> | |
# Changed to always round up size and always display up to 3 decimals. | |
# Shall also work with now retired python 2 language. | |
import math | |
def pp_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB', 'ZB', 'YB'], base=1000.0): | |
""" Returns a human readable string representation of bytes (decimal unit)""" | |
if bytes < base or len(units) == 1: | |
return str(math.ceil(bytes*base)/base) + units[0] | |
else: | |
return pp_size(bytes/base, units[1:], base) | |
def si_size(bytes): | |
""" Returns a human readable string representation of bytes (SI unit)""" | |
return pp_size(bytes, [' bytes','KiB','MiB','GiB','TiB', 'PiB', 'EiB', 'ZiB', 'YiB'], base=1024.0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment