python 转换容量单位 实现ls -h功能

功能1
把字节转换自适应转为其他单位(ls -h),超过1024投入高一级的区间,不足1024投入本级区间,如1000K是一个合理值,1030K就应该转换为1M,2050K应该转换为2M
功能2
把其他单位转换为字节
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re


def size_b_to_other(size):
    units = ['B', 'KB', 'MB', 'GB', 'TB']
    # 处理异常
    if size <= 0:
        return False

    # 遍历单位的位置并用取整除赋值
    for unit in units:
        if size >= 1024:
            size //= 1024
        else:
            size_h = '{} {}'.format(size, unit)
            return size_h

    size_h = '{} {}'.format(size, unit)
    return size_h


def size_other_to_b(size, unit):
    units = ['B', 'KB', 'MB', 'GB', 'TB']
    # 处理异常
    if size <= 0:
        return False

    # 找出单位的索引位置
    nu = units.index(unit)

    # 根据索引位置次幂在乘以系数
    size_h = int(size) * 1024 ** nu
    return int(size_h)


if __name__ == '__main__':
    """
    这里可以实现字节B转换其他单位或者其他单位转字节B,输入容量数字和单位后自动识别转换
    格式为10000B或者10M、1gb、20kb
    """
    data = input("请输要转换的容量和单位:")
    # 忽略大小写敏感
    size = re.sub("D", "", data)
    size = int(size)
    unit = ''.join(re.findall(r'[A-Za-z]', str.upper(data)))
    if unit == "B":
        result = size_b_to_other(size)
    else:
        # 支持单位简写
        if len(unit) == 1 :
            unit = unit + "B"
        result = size_other_to_b(size, unit)

    print(result)
原文地址:https://www.cnblogs.com/37yan/p/10710695.html