Skip to content

Instantly share code, notes, and snippets.

@jayd3e
Created April 3, 2015 15:48
Show Gist options
  • Save jayd3e/4cf5e8703773e7a31f9a to your computer and use it in GitHub Desktop.
Save jayd3e/4cf5e8703773e7a31f9a to your computer and use it in GitHub Desktop.
def humanize(size_bytes):
"""
Format a size in bytes into a 'human' file size, e.g. bytes, KB, MB, GB, TB, PB
Note that bytes/KB will be reported in whole numbers but MB and above will have greater precision
e.g. 1 byte, 43 bytes, 443 KB, 4.3 MB, 4.43 GB, etc
"""
if size_bytes == 1:
# because I really hate unnecessary plurals
return "1 byte"
suffixes_table = [('bytes', 0), ('KB', 0), ('MB', 1), ('GB', 2), ('TB', 2), ('PB', 2)]
num = float(size_bytes)
for suffix, precision in suffixes_table:
if num < 1024.0:
break
num /= 1024.0
if precision == 0:
formatted_size = "%d" % num
else:
formatted_size = str(round(num, ndigits=precision))
return "%s %s" % (formatted_size, suffix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment