python实现 文件数据 大小单位转换 人性化转换: B KB MB GB 文件大小 自动单位 - xd21303/Notebook GitHub Wiki

def humanized_size(size):
    '''
    人性化转化字节大小显示的单位
    '''
    def str_of_size(integer, remainder, level):
        if integer >= 1024:
            remainder = integer % 1024
            integer //= 1024
            level += 1
            return str_of_size(integer, remainder, level)
        else:
            return integer, remainder, level

    units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
    integer, remainder, level = str_of_size(size, 0, 0)
    if level+1 > len(units):
        level = -1
    return ('{}.{:>03d} {}'.format(integer, remainder, units[level]))
print(StrOfSize(11923))
print(StrOfSize(5463443))
print(StrOfSize(97736213623))

输出结果

11.659 KB
5.215 MB
91.024 GB

参考 https://blog.csdn.net/wskzgz/article/details/99293181