How to Convert Bytes to Appropriate Unit in Python

You sometimes get raw bytes for size of files. It’s hard to read and need a way to convert it. Here is the way you could do it.

def convert_size(size_bytes):
    if size_bytes == 0:
        return "0B"
    size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
    i = int(math.floor(math.log(size_bytes, 1024)))
    p = math.pow(1024, i)
    s = round(size_bytes / p, 2)
    return "%s %s" % (s, size_name[i])

I don’t claim that I wrote it but I found it somewhere on the Internet but I can’t remember the source…