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

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

    This is a compact version that converts B (bytes) to any higher order such MB, GB without using a lot of if...else in python. I use bit-wise to deal with this. Also it allows to return a float output if you trigger the parameter return_output in the function as True:

    import math
    
    def bytes_conversion(number, return_float=False):
    
        def _conversion(number, return_float=False):
    
            length_number = int(math.log10(number))
    
            if return_float:
    
               length_number = int(math.log10(number))
               return length_number // 3, '%.2f' % (int(number)/(1 << (length_number//3) *10))
    
            return length_number // 3, int(number) >> (length_number//3) * 10
    
        unit_dict = {
            0: "B",  1: "kB",
            2: "MB", 3: "GB",
            4: "TB", 5: "PB",
            6: "EB"
        }
    
        if return_float:
    
            num_length, number = _conversion(number, return_float=return_float)
    
        else:
            num_length, number = _conversion(number)
    
        return "%s %s" % (number, unit_dict[num_length])
    
    #Example usage:
    #print(bytes_conversion(491266116, return_float=True))
    

    This is only a few of my posts in StackOverflow. Please let me know if I have any errors or violations.

提交回复
热议问题