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

前端 未结 15 1662
轮回少年
轮回少年 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:37

    An output with no decimal places:

    >>> format_file_size(12345678)
    '11 MiB, 792 KiB, 334 bytes'
    
    format_file_size(
        def format_file_size(fsize):
            result = []
            units = {s: u for s, u in zip(reversed([2 ** n for n in range(0, 40, 10)]), ['GiB', 'MiB', 'KiB', 'bytes'])}
            for s, u in units.items():
                t = fsize // s
                if t > 0:
                    result.append('{} {}'.format(t, u))
                fsize = fsize % s
            return ', '.join(result) or '0 bytes'
    

提交回复
热议问题