Python字节单位转换之将字节转换为K M G T的示例
发布时间:2023-05-16 14:18:11
节转换为1KB,1MB,1GB,1TB
def convert_size(size_bytes):
# 定义字节单位列表
units = ['B', 'KB', 'MB', 'GB', 'TB']
# 获取字节数组长度
size_n = len(str(size_bytes))
# 计算转换次数
count = size_n // 3 if size_n % 3 == 0 else size_n // 3 + 1
# 循环转换大小
for i in range(count):
if size_bytes < 1024:
return f"{size_bytes:.2f}{units[i]}"
size_bytes /= 1024
# 如果字节数大于1TB,则返回TB
return f"{size_bytes:.2f}{units[-1]}"
# 测试
print(convert_size(1000)) # 1.00KB
print(convert_size(10241024)) # 9.77MB
print(convert_size(12345678900)) # 11.50GB
print(convert_size(12345678901234)) # 11.21TB
