Python format size application (converting B to KB, MB, GB, TB)

前端 未结 15 1637
轮回少年
轮回少年 2021-02-01 16:13

I am trying to write an application to convert bytes to kb to mb to gb to tb. Here\'s what I have so far:

def size_format(b):
    if b < 1000:
              r         


        
15条回答
  •  孤街浪徒
    2021-02-01 16:30

    Yet another humanbytes version, with no loops/if..else, in python3 syntax.

    Test numbers stolen from @whereisalext's answer.

    Mind you, it's still a sketch, e.g. if the numbers are large enough it will traceback.

    import math as m
    
    
    MULTIPLES = ["B", "k{}B", "M{}B", "G{}B", "T{}B", "P{}B", "E{}B", "Z{}B", "Y{}B"]
    
    
    def humanbytes(i, binary=False, precision=2):
        base = 1024 if binary else 1000
        multiple = m.trunc(m.log2(i) / m.log2(base))
        value = i / m.pow(base, multiple)
        suffix = MULTIPLES[multiple].format("i" if binary else "")
        return f"{value:.{precision}f} {suffix}"
    
    
    if __name__ == "__main__":
        sizes = [
            1, 1024, 500000, 1048576, 50000000, 1073741824, 5000000000,
            1099511627776, 5000000000000]
    
        for i in sizes:
            print(f"{i} == {humanbytes(i)}, {humanbytes(i, binary=True)}")
    

    Results:

    1 == 1.00 B, 1.00 B
    1024 == 1.02 kB, 1.00 kiB
    500000 == 500.00 kB, 488.28 kiB
    1048576 == 1.05 MB, 1.00 MiB
    50000000 == 50.00 MB, 47.68 MiB
    1073741824 == 1.07 GB, 1.00 GiB
    5000000000 == 5.00 GB, 4.66 GiB
    1099511627776 == 1.10 TB, 1.00 TiB
    5000000000000 == 5.00 TB, 4.55 TiB
    

    Update:

    As pointed out in comments (and as noted originally: "Mind you, it's still a sketch"), this code is slow and buggy. Please see @mitch-mcmabers 's answer.

    Update 2: I was also lying about having no ifs.

提交回复
热议问题