def sizeFormat(size, isDisk=False, precision=2):
'''
size format for human.
byte ---- (B)
kilobyte ---- (KB)
megabyte ---- (MB)
gigabyte ---- (GB)
terabyte ---- (TB)
petabyte ---- (PB)
exabyte ---- (EB)
zettabyte ---- (ZB)
yottabyte ---- (YB)
'''
units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
unit = 1000.0 if isDisk else 1024.0
if not(isinstance(size, float) or isinstance(size, int)):
raise TypeError('a float number or an integer number is required!')
li = [(unit**(i + 1), j) for i,j in enumerate(units)]
for i in li:
if size > i[0] and i[1] != li[-1][1]:
continue
else:
return f'{round(size*unit/i[0], precision)}{i[1]}'
Python implementation file size conversion
Guess you like
Origin www.cnblogs.com/mintx/p/10983668.html
Recommended
Ranking