Skip to content

Instantly share code, notes, and snippets.

@ElectroDrome
Last active April 29, 2024 20:08
Show Gist options
  • Save ElectroDrome/ec97c73db69e13e280300cb724a6d617 to your computer and use it in GitHub Desktop.
Save ElectroDrome/ec97c73db69e13e280300cb724a6d617 to your computer and use it in GitHub Desktop.
Python: Format a number of bytes into a human readable format
from math import log
def format_bytes(n,pow=0,b=1024,u='B',pre=['']+[p+'i'for p in'KMGTPEZY']):
pow,n=min(int(log(max(n*b**pow,1),b)),len(pre)-1),n*b**pow
return "%%.%if %%s%%s"%abs(pow%(-pow-1))%(n/b**float(pow),pre[pow],u)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment