Created
September 9, 2012 14:15
-
-
Save danlmyers/3684595 to your computer and use it in GitHub Desktop.
python humanize bytes
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
#Humanize byte size figures | |
def humanize_bytes(bytesize, precision=2): | |
abbrevs = ( | |
(1<<50, 'PB'), | |
(1<<40, 'TB'), | |
(1<<30, 'GB'), | |
(1<<20, 'MB'), | |
(1<<10, 'kB'), | |
(1, 'bytes') | |
) | |
if bytesize == 1: | |
return '1 byte' | |
for factor, suffix in abbrevs: | |
if bytesize >= factor: | |
break | |
return '%.*f %s' % (precision, bytesize / factor, suffix) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Tried out this code. I was passing in longs from os.stat for bytesize and factor is going to be either int or long, so you always get whole numbers. I'm not sure what the point of the precision was in that case, so I changed factor to be a float. Also, having a decimal point for bytes didn't make sense to me. If those things matter for you, try this: