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

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

    I have improved, in my opininion, @whereisalext answer to have a somewhat more generic function which does not require one to add more if statements once more units are going to be added:

    AVAILABLE_UNITS = ['bytes', 'KB', 'MB', 'GB', 'TB']
    
    def get_amount_and_unit(byte_amount):
        for index, unit in enumerate(AVAILABLE_UNITS):
            lower_threshold = 0 if index == 0 else 1024 ** (index - 1)
            upper_threshold = 1024 ** index
            if lower_threshold <= byte_amount < upper_threshold:
                if lower_threshold == 0:
                    return byte_amount, unit
                else:
                    return byte_amount / lower_threshold, AVAILABLE_UNITS[index - 1]
        # Default to the maximum
        max_index = len(AVAILABLE_UNITS) - 1
        return byte_amount / (1024 ** max_index), AVAILABLE_UNITS[max_index]
    

    Do note that this differs slightly frrom @whereisalext's algo:

    • This returns a tuple containing the converted amount at the first index and the unit at the second index
    • This does not try to differ between a singular and multiple bytes (1 bytes is therefore an output of this approach)

提交回复
热议问题