python3 处理文件大小,自动选择合适单位

内容来源于chatgpt

def format_size(bytes):
    """
    将字节大小转换为适当的单位(KB, MB, GB等),支持负数。

    :param bytes: 原始字节大小,可以为负数
    :return: 字符串,格式化后的大小和单位
    """
    # 定义单位和阈值
    units = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
    
    # 记录负号
    sign = "-" if bytes < 0 else ""
    
    # 转为正数进行计算
    size = abs(bytes)
    index = 0

    # 每次除以1024,直到大小合适或达到最大单位
    while size >= 1024 and index < len(units) - 1:
        size /= 1024.0
        index += 1

    # 格式化输出,保留两位小数,并加上负号(如有)
    return f"{sign}{size:.2f} {units[index]}"

# 示例使用
print(format_size(123456789))   # 输出: 117.74 MB
print(format_size(-1024))       # 输出: -1.00 KB
print(format_size(1048576))     # 输出: 1.00 MB
print(format_size(-987654321))  # 输出: -941.90 MB
posted @   BrianSun  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2023-11-12 debian12 安装ch343驱动
2020-11-12 ffmpeg -使用总结
点击右上角即可分享
微信分享提示