Convert File Size in Bytes into Human Readable String using Python

Calculate by formula

def format_file_size(size, decimals=2, binary_system=True):
    if binary_system:
        units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB']
        largest_unit = 'YiB'
        step = 1024
    else:
        units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB']
        largest_unit = 'YB'
        step = 1000

    for unit in units:
        if size < step:
            return ('%.' + str(decimals) + 'f %s') % (size, unit)
        size /= step

    return ('%.' + str(decimals) + 'f %s') % (size, largest_unit)


print(format_file_size(5000))            # 4.88 KiB
print(format_file_size(5000, 8))         # 4.88281250 KiB
print(format_file_size(5000, 2, False))  # 5.00 kB

The 2 Comments Found

  1. Avatar
    Johannes Braunias Reply

    Isn't it the other way round?
    MiB = 1000 Bytes and
    MB = 1024 Bytes

    • Avatar
      lindevs Reply

      Hi, Johannes
      1 MB = 1000 kB, 1 kB = 1000 bytes
      1 MiB = 1024 KiB, 1 KiB = 1024 bytes
      A mega prefix in the megabyte (MB) and kilo prefix in the kilobyte (kB) comes from the decimal system that is based on powers of 10 (10^n).
      Meanwhile, a mebi prefix in the mebibyte (MiB) and kibi prefix in the kibibyte (KiB) comes from the binary system that is based powers of 2 (2^n).

Leave a Comment

Cancel reply

Your email address will not be published.