Python 文件大小(Byte)可读性转化(KB、MB、GB、TB)

Python 文件大小可读性转化

  • file_size_exchange.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time:2023/5/12 17:52
# @Software:PyCharm
__author__ = "JentZhang"

KB = 1024
MB = KB * KB
GB = MB * KB
TB = GB * KB


def format_byte_repr(byte_num):
    """
    size转换
    :param byte_num: 单位Byte
    :return:
    """
    try:
        if isinstance(byte_num, str):
            byte_num = int(byte_num)
        if byte_num > TB:
            result = '%s TB' % round(byte_num / TB, 2)
        elif byte_num > GB:
            result = '%s GB' % round(byte_num / GB, 2)
        elif byte_num > MB:
            result = '%s MB' % round(byte_num / MB, 2)
        elif byte_num > KB:
            result = '%s KB' % round(byte_num / KB, 2)
        else:
            result = '%s B' % byte_num
        return result
    except Exception as e:
        print(e.args)
        return byte_num

if __name__ == '__main__':
    print(format_byte_repr("8869"))

结果

8.66 KB
posted on 2023-05-12 18:00  JentZhang  阅读(480)  评论(0)    收藏  举报