Skip to content

Instantly share code, notes, and snippets.

@brunomsantiago
Last active April 6, 2021 19:37
Show Gist options
  • Save brunomsantiago/8a9eb13c7e6f19454894036af6f23813 to your computer and use it in GitHub Desktop.
Save brunomsantiago/8a9eb13c7e6f19454894036af6f23813 to your computer and use it in GitHub Desktop.
human_readable_size
import math
def human_readable_size(size_bytes, base=1024, decimal_places=2):
suffixes = 'B KB MB GB TB PB EB ZB YB'.split(' ')
if size_bytes == 0:
return '0B'
magnitude_index = int(math.floor(math.log(size_bytes, base)))
magnitude_bytes = math.pow(base, magnitude_index)
size = size_bytes / magnitude_bytes
suffix = suffixes[magnitude_index]
return f'{size:.{decimal_places}f} {suffix}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment