Skip to content

Instantly share code, notes, and snippets.

@denisrasulev
Last active January 30, 2019 23:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denisrasulev/9ef0356fdea97e3ac7a06a46fcdaf795 to your computer and use it in GitHub Desktop.
Save denisrasulev/9ef0356fdea97e3ac7a06a46fcdaf795 to your computer and use it in GitHub Desktop.
Humanize Bytes Function
def humanize_bytes(bytes, precision=1):
"""Return a humanized string representation of a number of bytes.
Assumes `from __future__ import division`.
>>> humanize_bytes(1)
'1 byte'
>>> humanize_bytes(1024)
'1.0 kB'
>>> humanize_bytes(1024*123)
'123.0 kB'
>>> humanize_bytes(1024*12342)
'12.1 MB'
>>> humanize_bytes(1024*12342,2)
'12.05 MB'
>>> humanize_bytes(1024*1234,2)
'1.21 MB'
>>> humanize_bytes(1024*1234*1111,2)
'1.31 GB'
>>> humanize_bytes(1024*1234*1111,1)
'1.3 GB'
"""
abbrevs = (
(1 << 50L, 'PB'),
(1 << 40L, 'TB'),
(1 << 30L, 'GB'),
(1 << 20L, 'MB'),
(1 << 10L, 'kB'),
(1, 'bytes')
)
if bytes == 1:
return '1 byte'
for factor, suffix in abbrevs:
if bytes >= factor:
break
return '%.*f %s' % (precision, bytes / factor, suffix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment