Skip to content

Instantly share code, notes, and snippets.

@dayyass
Created July 25, 2021 08:25
Show Gist options
  • Save dayyass/78d99343231196c2114036f760cb20dc to your computer and use it in GitHub Desktop.
Save dayyass/78d99343231196c2114036f760cb20dc to your computer and use it in GitHub Desktop.
Convert bytes to human readable format.
def humanize_bytes(bytes: int, suffix: str = "B") -> str:
"""
Convert bytes to human readable format.
:param int bytes: number of bytes.
:param str suffix: bytes suffix.
:return: human readable size.
:rtype: str
"""
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes >= 1024:
bytes /= 1024
else:
break
return f"{bytes:.2f}{unit}{suffix}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment