製做命令行工具過程當中,因須要展現文件大小,因此造了個輪子,實現瞭如下byte可視化轉換。python
若是哪位仁兄知道有現成的輪子,勞煩留言告知一聲。工具
如下是代碼實現。測試
def unit_conversion(size): ratio = 2 ** 10 units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] level = 0 size = int(size) if size < 0: try: raise ValueError except ValueError as e: print('Please enter the correct parameters', repr(e)) for unit in units: if size > ratio: size = size / ratio level += 1 continue else: size = '%.1f %s' % (size, unit) return size size = '這個大小多少有點過度' return size # 如下是測試部分 test0 = unit_conversion(230) test1 = unit_conversion(1500) test2 = unit_conversion(2823230) test3 = unit_conversion(8231283128) test4 = unit_conversion(10239841023123) test5 = unit_conversion(502938748172301283017) test6 = unit_conversion(923619287389872013891231) test7 = unit_conversion(72379812387401293812847821631246) print(f'test0 : {test0}') print(f'test1 : {test1}') print(f'test2 : {test2}') print(f'test3 : {test3}') print(f'test4 : {test4}') print(f'test5 : {test5}') print(f'test6 : {test6}') print(f'test7 : {test7}')
test0 : 230.0 B test1 : 1.5 KB test2 : 2.7 MB test3 : 7.7 GB test4 : 9.3 TB test5 : 436.2 EB test6 : 782.3 ZB test7 : 這個大小多少有點過度