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

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

    A very simple solution would be:

    SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
    
    def get_readable_file_size(size_in_bytes):
        index = 0
        while size_in_bytes >= 1024:
            size_in_bytes /= 1024
            index += 1
        try:
            return f'{size_in_bytes} {SIZE_UNITS[index]}'
        except IndexError:
            return 'File too large'
    

提交回复
热议问题