Skip to content

Instantly share code, notes, and snippets.

@brandon-wallace
Last active September 28, 2021 19:10
Show Gist options
  • Save brandon-wallace/6718303e3fec742a709b521b7080cf5e to your computer and use it in GitHub Desktop.
Save brandon-wallace/6718303e3fec742a709b521b7080cf5e to your computer and use it in GitHub Desktop.
def convert_bytes(bytes, unit):
'''
Convert bytes to more human readable format.
For sizes above 1 KB display amount in kilobytes.
For sizes above 1 MB display amount in megabytes.
For sizes above 1 GB display amount in gigabytes.
For sizes above 1 TB display...
'''
unit = unit.lower()
if bytes >= 1024:
unit = 'k'
if bytes >= 1048576:
unit = 'm'
if bytes >= 1048576000:
unit = 'g'
if bytes >= 1099511627776:
unit = 't'
if bytes >= 1125899906842618:
unit = 'p'
if bytes >= 1152921504606851800:
unit = 'e'
factor = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
return f'{bytes / (1024 ** factor[unit]):.2f} {unit.upper()}B'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment