Python字节单位转换(将字节转换为K M G T)
defbytes_to_human(n):
symbols=('K','M','G','T','P','E','Z','Y')
prefix={}
fori,sinenumerate(symbols):
prefix[s]=1<<(i+1)*10
forsinreversed(symbols):
ifn>=prefix[s]:
value=float(n)/prefix[s]
return'%.1f%s'%(value,s)
return'%sB'%n
python编写的储存单位转换代码(以字节(B)为单位)
defbytes(bytes):
ifbytes<1024:#比特
bytes=str(round(bytes,2))+'B'#字节
elifbytes>=1024andbytes<1024*1024:
bytes=str(round(bytes/1024,2))+'KB'#千字节
elifbytes>=1024*1024andbytes<1024*1024*1024:
bytes=str(round(bytes/1024/1024,2))+'MB'#兆字节
elifbytes>=1024*1024*1024andbytes<1024*1024*1024*1024:
bytes=str(round(bytes/1024/1024/1024,2))+'GB'#千兆字节
elifbytes>=1024*1024*1024*1024andbytes<1024*1024*1024*1024*1024:
bytes=str(round(bytes/1024/1024/1024/1024,2))+'TB'#太字节
elifbytes>=1024*1024*1024*1024*1024andbytes<1024*1024*1024*1024*1024*1024:
bytes=str(round(bytes/1024/1024/1024/1024/1024,2))+'PB'#拍字节
elifbytes>=1024*1024*1024*1024*1024*1024andbytes<1024*1024*1024*1024*1024*1024*1024:
bytes=str(round(bytes/1024/1024/1024/1024/1024/1024,2))+'EB'#艾字节
returnbytes
if__name__=='__main__':
print('0:'+bytes(0))
print('1:'+bytes(1))
print('2:'+bytes(10))
print('3:'+bytes(100))
print('4:'+bytes(1000))
print('5:'+bytes(10000))
print('6:'+bytes(100000))
print('7:'+bytes(1000000))
print('8:'+bytes(10000000))
print('9:'+bytes(100000000))
print('10:'+bytes(1000000000))
print('11:'+bytes(10000000000))
print('12:'+bytes(100000000000))
print('13:'+bytes(1000000000000))
print('14:'+bytes(10000000000000))
print('15:'+bytes(100000000000000))
print('16:'+bytes(1000000000000000))
print('17:'+bytes(10000000000000000))
print('18:'+bytes(100000000000000000))
print('19:'+bytes(1000000000000000000))
print('20:'+bytes(10000000000000000000))
print('20:'+bytes(100000000000000000000))
print('20:'+bytes(1000000000000000000000))
测试:
"D:\ProgramFiles\Python\Python36\python.exe"C:/Users/Jochen/PycharmProjects/mysite/bytes.py
0:0B
1:1B
2:10B
3:100B
4:1000B
5:9.77KB
6:97.66KB
7:976.56KB
8:9.54MB
9:95.37MB
10:953.67MB
11:9.31GB
12:93.13GB
13:931.32GB
14:9.09TB
15:90.95TB
16:909.49TB
17:8.88PB
18:88.82PB
19:888.18PB
20:8.67EB
20:86.74EB
20:867.36EBProcessfinishedwithexitcode0
到此这篇关于Python字节单位转换(将字节转换为KMGT)的文章就介绍到这了,更多相关Python字节单位转换内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。