Skip to content

Instantly share code, notes, and snippets.

@ElectroDrome
Last active April 29, 2024 20:08
Show Gist options
  • Save ElectroDrome/fbc14db2ea5be7568e0f726a81d27630 to your computer and use it in GitHub Desktop.
Save ElectroDrome/fbc14db2ea5be7568e0f726a81d27630 to your computer and use it in GitHub Desktop.
Python: Format a number of bytes into a human readable format (non looping solution)
def format_bytes(num, suffix='B'):
magnitude = int(math.floor(math.log(num, 1024)))
val = num / math.pow(1024, magnitude)
if magnitude > 7:
return '{:.1f}{}{}'.format(val, 'Yi', suffix)
return '{:3.1f}{}{}'.format(val, ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi'][magnitude], suffix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment