Skip to content

Instantly share code, notes, and snippets.

@danlmyers
Created September 9, 2012 14:15
Show Gist options
  • Save danlmyers/3684595 to your computer and use it in GitHub Desktop.
Save danlmyers/3684595 to your computer and use it in GitHub Desktop.
python humanize bytes
#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)
@jhillacre
Copy link

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:

def humanize_bytes(bytesize, precision=2):
    """
    Humanize byte size figures
    """
    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
    if factor == 1:
        precision = 0
    return '%.*f %s' % (precision, bytesize / float(factor), suffix)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment