Python字节单位转换实例
作者:_荣耀之路_ 时间:2023-07-18 07:09:16
我就废话不多说了,直接上代码!
from enum import Enum
class Values():
values={'B':1}
@staticmethod
def getValues():
if len(Values.values)<=1:
kbunits=['KB','MB','GB','TB','PB','EB','ZB','YB','BB','NB','DB']
kibunits=['KiBi','MiB','GiB','TiB','PiB','EiB','ZiB','YiB','BiB','NiB','DiB']
for index,unit in enumerate(kibunits):
Values.values[unit]=1<<(index+1)*10
for index,unit in enumerate(kbunits):
Values.values[unit]=10**((index+1)*3)
return Values.values
@staticmethod
def get(key):
return Values.getValues().get(key)
class Units(Enum):
def __new__(cls,name):
obj = object.__new__(cls)
print (name)
obj._value_=Values.get(name)
return obj
B=('B')
KB=('KB')
KiB=('KiBi')
MB=('MB')
MiB=('MiB')
GB=('GB')
GiB=('GiB')
TB=('TB')
TiB=('TiB')
PB=('PB')
PiB=('PiB')
EB=('EB')
EiB=('EiB')
ZB=('ZB')
ZiB=('ZiB')
YB=('YB')
YiB=('YiB')
BB=('BB')
BiB=('BiB')
NB=('NB')
NiB=('NiB')
DB=('DB')
DiB=('DiB')
class ByteUnitConversionUtil():
__defaultformat="%.5f"
@staticmethod
def convert(value,unit=Units.B,format=__defaultformat):
if(unit==Units.B):
return str(value).split(".",2)[0]+unit.name
else:
return (format % (value/unit.value))+unit.name
if __name__=="__main__":
print(ByteUnitConversionUtil.convert(12313213453,Units.KiB,"%.2f"))
来源:https://blog.csdn.net/asty9000/article/details/79793186
标签:Python,字节单位,转换
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Prometheus和NodeExporter安装监控数据说明
2022-09-22 00:55:40
![](https://img.aspxhome.com/file/2023/1/114711_0s.jpg)
Python 基于jwt实现认证机制流程解析
2022-07-15 00:25:30
详解Django中间件执行顺序
2023-01-27 20:30:00
![](https://img.aspxhome.com/file/2023/0/85150_0s.png)
数据库名词解释
2008-09-12 17:28:00
Python3结合Dlib实现人脸识别和剪切
2023-01-10 01:28:48
![](https://img.aspxhome.com/file/2023/6/76036_0s.png)
如何在Python 游戏中模拟引力
2021-11-28 21:51:27
pycharm无法安装cv2模块问题及解决方案
2023-02-14 21:20:49
![](https://img.aspxhome.com/file/2023/9/133819_0s.png)
基于javascript实现全国省市二级联动下拉选择菜单
2023-09-14 06:08:52
![](https://img.aspxhome.com/file/2023/3/56303_0s.jpg)
Python集合的增删改查操作
2023-09-30 00:48:18
什么是 XML Web Service
2008-09-05 17:21:00
python SMTP实现发送带附件电子邮件
2023-09-29 11:31:54
sql 版本详解 让你认识跟sql2000的区别
2024-01-26 03:58:34
python 获取当前目录下的文件目录和文件名实例代码详解
2022-07-21 21:31:25
使用python实现CGI环境搭建过程解析
2022-11-01 11:41:26
![](https://img.aspxhome.com/file/2023/1/128611_0s.png)
Python中的取模运算方法
2023-11-10 04:39:56
![](https://img.aspxhome.com/file/2023/1/90321_0s.jpg)
安装dbus-python的简要教程
2021-09-07 10:09:43
python爬取51job中hr的邮箱
2022-11-06 14:00:54
git-pycharm配置.ignore文件的详细过程
2023-04-18 23:05:57
![](https://img.aspxhome.com/file/2023/8/132488_0s.png)
如何用Python提取10000份log中的产品信息
2023-06-30 06:23:21
![](https://img.aspxhome.com/file/2023/2/118632_0s.png)
python人工智能算法之决策树流程示例详解
2022-02-27 17:34:31