Python格式大小的应用程序(将B转换为KB,MB,GB,TB) [英] Python format size application (converting B to KB, MB, GB, TB)
本文介绍了Python格式大小的应用程序(将B转换为KB,MB,GB,TB)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个将字节转换为kb转换为mb转换为gb转换为tb的应用程序. 这是我到目前为止的内容:
I am trying to write an application to convert bytes to kb to mb to gb to tb. Here's what I have so far:
def size_format(b):
if b < 1000:
return '%i' % b + 'B'
elif 1000 <= b < 1000000:
return '%.1f' % float(b/1000) + 'KB'
elif 1000000 <= b < 1000000000:
return '%.1f' % float(b/1000000) + 'MB'
elif 1000000000 <= b < 1000000000000:
return '%.1f' % float(b/1000000000) + 'GB'
elif 1000000000000 <= b:
return '%.1f' % float(b/1000000000000) + 'TB'
问题是,当我尝试应用程序时,在十进制清零后我得到了所有东西.
例子
size_format(623)
产量
'623B'
但使用size_format(6200)
,
而不是获得"6.2kb"
我正在获取"6.0kb".
有什么想法吗?
The problem is, when I try the application I get everything after the decimal zeroing out.
example
size_format(623)
yields
'623B'
but with size_format(6200)
,
instead of getting '6.2kb'
I'm getting '6.0kb'.
Any ideas why?
推荐答案
Bryan_Rch答案的固定版本:
Fixed version of Bryan_Rch's answer:
def format_bytes(size):
# 2**10 = 1024
power = 2**10
n = 0
power_labels = {0 : '', 1: 'kilo', 2: 'mega', 3: 'giga', 4: 'tera'}
while size > power:
size /= power
n += 1
return size, power_labels[n]+'bytes'
这篇关于Python格式大小的应用程序(将B转换为KB,MB,GB,TB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文