有时候需要计算一个文件的大小,但是 473234234 B 我们一眼也看不出来有多大,下面的程序可以帮助你快速转换。
# -*- coding: utf-8 -*-
import math
def bit_conversion(size, dot=2):
size = float(size)
# 位 比特 bit
if 0 <= size < 1:
human_size = str(round(size / 0.125, dot)) + ' b'
# 字节 字节 Byte
elif 1 <= size < 1024:
human_size = str(round(size, dot)) + ' B'
# 千字节 千字节 Kilo Byte
elif math.pow(1024, 1) <= size < math.pow(1024, 2):
human_size = str(round(size / math.pow(1024, 1), dot)) + ' KB'
# 兆字节 兆 Mega Byte
elif math.pow(1024, 2) <= size < math.pow(1024, 3):
human_size = str(round(size / math.pow(1024, 2), dot)) + ' MB'
# 吉字节 吉 Giga Byte
elif math.pow(1024, 3) <= size < math.pow(1024, 4):
human_size = str(round(size / math.pow(1024, 3), dot)) + ' GB'
# 太字节 太 Tera Byte
elif math.pow(1024, 4) <= size < math.pow(1024, 5):
human_size = str(round(size / math.pow(1024, 4), dot)) + ' TB'
# 拍字节 拍 Peta Byte
elif math.pow(1024, 5) <= size < math.pow(1024, 6):
human_size = str(round(size / math.pow(1024, 5), dot)) + ' PB'
# 艾字节 艾 Exa Byte
elif math.pow(1024, 6) <= size < math.pow(1024, 7):
human_size = str(round(size / math.pow(1024, 6), dot)) + ' EB'
# 泽它字节 泽 Zetta Byte
elif math.pow(1024, 7) <= size < math.pow(1024, 8):
human_size = str(round(size / math.pow(1024, 7), dot)) + ' ZB'
# 尧它字节 尧 Yotta Byte
elif math.pow(1024, 8) <= size < math.pow(1024, 9):
human_size = str(round(size / math.pow(1024, 8), dot)) + ' YB'
# 千亿亿亿字节 Bront Byte
elif math.pow(1024, 9) <= size < math.pow(1024, 10):
human_size = str(round(size / math.pow(1024, 9), dot)) + ' BB'
# 百万亿亿亿字节 Dogga Byte
elif math.pow(1024, 10) <= size < math.pow(1024, 11):
human_size = str(round(size / math.pow(1024, 10), dot)) + ' NB'
# 十亿亿亿亿字节 Dogga Byte
elif math.pow(1024, 11) <= size < math.pow(1024, 12):
human_size = str(round(size / math.pow(1024, 11), dot)) + ' DB'
# 万亿亿亿亿字节 Corydon Byte
elif math.pow(1024, 12) <= size:
human_size = str(round(size / math.pow(1024, 12), dot)) + ' CB'
# 负数
else:
raise ValueError('bit_conversion Error')
return human_size
print(bit_conversion(473234234))