Skip to content

Instantly share code, notes, and snippets.

@ElectroDrome
Last active April 29, 2024 20:10
Show Gist options
  • Save ElectroDrome/365347f9d71154a517d71b3655a768f7 to your computer and use it in GitHub Desktop.
Save ElectroDrome/365347f9d71154a517d71b3655a768f7 to your computer and use it in GitHub Desktop.
Python: Format a number of bytes into a human readable format (non looping solution)
from math import log
unit_list = zip(['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'], [0, 0, 1, 2, 2, 2])
def format_bytes(num):
if num > 1:
exponent = min(int(log(num, 1024)), len(unit_list) - 1)
quotient = float(num) / 1024**exponent
unit, num_decimals = unit_list[exponent]
format_string = '{:.%sf} {}' % (num_decimals)
return format_string.format(quotient, unit)
if num == 0:
return '0 bytes'
if num == 1:
return '1 byte'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment