Created
October 3, 2013 18:17
-
-
Save kkinder/6814448 to your computer and use it in GitHub Desktop.
Show the user a friendly size. Adapted with larger sizes from http://stackoverflow.com/a/1094933
This file contains 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
def friendly_size(length): | |
""" | |
Returns *binary* human-friendly size. Goes all the way up to YB. | |
>>> friendly_size(0) | |
'0 bytes' | |
>>> friendly_size(1024) | |
'1.0 KB' | |
>>> friendly_size(1524) | |
'1.5 KB' | |
>>> friendly_size(1024**4) | |
'1.0 TB' | |
>>> friendly_size(1024**4 + (1024**4/3)) | |
'1.3 TB' | |
>>> friendly_size(1024**3*2.5) | |
'2.5 GB' | |
""" | |
for unit in ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']: | |
if length < 1024.0 or unit == 'YB': | |
if unit == 'bytes': | |
return "%i %s" % (length, unit) | |
else: | |
return "%3.1f %s" % (length, unit) | |
length /= 1024.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment