impl/python/format_file_size.py
1,111 bytes · the Python implementation · view raw
UNITS = ("KB", "MB", "GB", "TB")
def format_file_size(bytes: int) -> str:
"""A size for people: "512 bytes", "1.5MB". Units of 1024, one decimal
place rounded half up only when the size is not a whole number of the
unit; a size that rounds up to 1024 of a unit is one of the next."""
if isinstance(bytes, bool) or not isinstance(bytes, int):
raise ValueError("size must be a whole number of bytes, got %r" % (bytes,))
if bytes < 0:
raise ValueError("size must be 0 or more, got %d" % bytes)
if bytes == 1:
return "1 byte"
if bytes < 1024:
return "%d bytes" % bytes
power = 1
while power < len(UNITS) and bytes >= 1024 ** (power + 1):
power += 1
unit = 1024 ** power
tenths = (bytes * 10 + unit // 2) // unit
if tenths >= 10240 and power < len(UNITS):
power += 1
unit = 1024 ** power
tenths = (bytes * 10 + unit // 2) // unit
whole, fraction = divmod(tenths, 10)
if fraction == 0:
return "%d%s" % (whole, UNITS[power - 1])
return "%d.%d%s" % (whole, fraction, UNITS[power - 1])