Skip to content

Instantly share code, notes, and snippets.

@ElectroDrome
Last active April 29, 2024 20:08
Show Gist options
  • Save ElectroDrome/162d4591fd5e00b76e6df0858272ff39 to your computer and use it in GitHub Desktop.
Save ElectroDrome/162d4591fd5e00b76e6df0858272ff39 to your computer and use it in GitHub Desktop.
Python: Format a number of bytes into a human readable format
def format_bytes(n): # Convert a number of bytes into a human readable format
symbols = ('KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.3f%s' % (value, s) # 3 digits
return "%sB" % n
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment