Last active
April 29, 2024 20:08
-
-
Save ElectroDrome/162d4591fd5e00b76e6df0858272ff39 to your computer and use it in GitHub Desktop.
Python: Format a number of bytes into a human readable format
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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