扫二维码与项目经理沟通
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流
这篇文章将为大家详细讲解有关Python字节单位转换之将字节转换为K M G T的示例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
成都创新互联是一家集网站建设,云龙企业网站建设,云龙品牌网站建设,网站定制,云龙网站建设报价,网络营销,网络优化,云龙网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。def bytes_to_human(n): symbols = ('K','M','G','T','P','E','Z','Y') prefix = {} for i,s in enumerate(symbols): prefix[s] = 1 << (i + 1) * 10 for s in reversed(symbols): if n >= prefix[s]: value = float(n) / prefix[s] return '%.1f%s' % (value,s) return '%sB' % n
def bytes(bytes): if bytes < 1024: #比特 bytes = str(round(bytes, 2)) + ' B' #字节 elif bytes >= 1024 and bytes < 1024 * 1024: bytes = str(round(bytes / 1024, 2)) + ' KB' #千字节 elif bytes >= 1024 * 1024 and bytes < 1024 * 1024 * 1024: bytes = str(round(bytes / 1024 / 1024, 2)) + ' MB' #兆字节 elif bytes >= 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024: bytes = str(round(bytes / 1024 / 1024 / 1024, 2)) + ' GB' #千兆字节 elif bytes >= 1024 * 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024 * 1024: bytes = str(round(bytes / 1024 / 1024 / 1024 / 1024, 2)) + ' TB' #太字节 elif bytes >= 1024 * 1024 * 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024 * 1024 * 1024: bytes = str(round(bytes / 1024 / 1024 / 1024 / 1024 / 1024, 2)) + ' PB' #拍字节 elif bytes >= 1024 * 1024 * 1024 * 1024 * 1024 * 1024 and bytes < 1024 * 1024 * 1024 * 1024 * 1024 * 1024 * 1024: bytes = str(round(bytes / 1024 / 1024 / 1024 / 1024 / 1024 /1024, 2)) + ' EB' #艾字节 return bytes 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:\Program Files\Python\Python36\python.exe" C:/Users/Jochen/PycharmProjects/mysite/bytes.py
0:0 B
1:1 B
2:10 B
3:100 B
4:1000 B
5:9.77 KB
6:97.66 KB
7:976.56 KB
8:9.54 MB
9:95.37 MB
10:953.67 MB
11:9.31 GB
12:93.13 GB
13:931.32 GB
14:9.09 TB
15:90.95 TB
16:909.49 TB
17:8.88 PB
18:88.82 PB
19:888.18 PB
20:8.67 EB
20:86.74 EB
20:867.36 EBProcess finished with exit code 0
关于“Python字节单位转换之将字节转换为K M G T的示例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
我们在微信上24小时期待你的声音
解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流