How to convert bytes to KB, MB and GB with Python ready-to-use function?


How to convert bytes to KB, MB and GB?

Ready to use Python function to convert any number to bytes, KB, MB, and GB:

def convert_bytes(bytes):
    # this function will convert bytes to MB.... GB... etc
    units = ['bytes', 'KB', 'MB', 'GB', 'TB']
    conversion_factor = 1024
    unit_index = 0
    while bytes >= conversion_factor and unit_index < len(units) - 1:
        bytes /= conversion_factor
        unit_index += 1
    return f"{bytes:.2f} {units[unit_index]}"

Write your main code as a sample below,

result = convert_bytes(423 * 721 * 28)
print(f"{num_bytes} bytes is equal to {result}.")

The output of the code is,

8539524 bytes is equal to 8.14 MB

How does the function work?

The function convert_bytes takes an argument bytes which is a numerical value representing the number of bytes. The function then converts the number of bytes to KB, MB, GB, or TB, by dividing the number of bytes by a conversion factor of 1024.

The function uses a while loop to keep dividing the number of bytes by the conversion factor until either the number of bytes is less than the conversion factor or all of the units have been used. The index of the current unit is stored in the unit_index variable, which is incremented after each division.

Finally, the function returns a string with the converted number of bytes, rounded to 2 decimal places, followed by the appropriate unit, which is looked up in the units list using the unit_index. The string is generated using an f-string, which is a string literal that can contain expressions that are evaluated and replaced with their values at runtime.

Leave a Reply

Your email address will not be published. Required fields are marked *