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

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

    I have quite readable function to convert bytes into greater units:

    def bytes_2_human_readable(number_of_bytes):
        if number_of_bytes < 0:
            raise ValueError("!!! number_of_bytes can't be smaller than 0 !!!")
    
        step_to_greater_unit = 1024.
    
        number_of_bytes = float(number_of_bytes)
        unit = 'bytes'
    
        if (number_of_bytes / step_to_greater_unit) >= 1:
            number_of_bytes /= step_to_greater_unit
            unit = 'KB'
    
        if (number_of_bytes / step_to_greater_unit) >= 1:
            number_of_bytes /= step_to_greater_unit
            unit = 'MB'
    
        if (number_of_bytes / step_to_greater_unit) >= 1:
            number_of_bytes /= step_to_greater_unit
            unit = 'GB'
    
        if (number_of_bytes / step_to_greater_unit) >= 1:
            number_of_bytes /= step_to_greater_unit
            unit = 'TB'
    
        precision = 1
        number_of_bytes = round(number_of_bytes, precision)
    
        return str(number_of_bytes) + ' ' + unit
    

提交回复
热议问题