Skip to content

Instantly share code, notes, and snippets.

@t0rik
Created November 29, 2023 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t0rik/df4817577834d15d648d45f885b14d05 to your computer and use it in GitHub Desktop.
Save t0rik/df4817577834d15d648d45f885b14d05 to your computer and use it in GitHub Desktop.
Bytes conversion Python.
import psutil
def bytes2human(n):
# >>> bytes2human(10000)
# '9.8K'
# >> bytes2human(100001221)
# '95.4M'
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i + 1) * 10
for s in reversed(symbols):
if abs(n) >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
total = psutil.disk_usage('/').total
print(total)
print(bytes2human(total))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment