Here is what I use:
import math
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
NB : size should be sent in Bytes.
Answer from James Sapam on Stack OverflowHere is what I use:
import math
def convert_size(size_bytes):
if size_bytes == 0:
return "0B"
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
i = int(math.floor(math.log(size_bytes, 1024)))
p = math.pow(1024, i)
s = round(size_bytes / p, 2)
return "%s %s" % (s, size_name[i])
NB : size should be sent in Bytes.
There is hurry.filesize that will take the size in bytes and make a nice string out if it.
>>> from hurry.filesize import size
>>> size(11000)
'10K'
>>> size(198283722)
'189M'
Or if you want 1K == 1000 (which is what most users assume):
>>> from hurry.filesize import size, si
>>> size(11000, system=si)
'11K'
>>> size(198283722, system=si)
'198M'
It has IEC support as well (but that wasn't documented):
>>> from hurry.filesize import size, iec
>>> size(11000, system=iec)
'10Ki'
>>> size(198283722, system=iec)
'189Mi'
Because it's written by the Awesome Martijn Faassen, the code is small, clear and extensible. Writing your own systems is dead easy.
Here is one:
mysystem = [
(1024 ** 5, ' Megamanys'),
(1024 ** 4, ' Lotses'),
(1024 ** 3, ' Tons'),
(1024 ** 2, ' Heaps'),
(1024 ** 1, ' Bunches'),
(1024 ** 0, ' Thingies'),
]
Used like so:
>>> from hurry.filesize import size
>>> size(11000, system=mysystem)
'10 Bunches'
>>> size(198283722, system=mysystem)
'189 Heaps'
Videos
I am using scrapy to scrape some data for my work and I am quite new to python.
Here is how my code looks;
........
data_list = []
........
for item in data:
name = item["name']
id = item["id"]
size = item["size"]
data = {
"name": name,
"id": id,
"size": size
}
data_list.append(data)
return data_listEverything wroks fine but the size part returns in bytes form. Here is how it looks;
[{"name": "n1", "category": "c1", "size": "2205728801"},
{"name": "n2", "category": "c2", "size": "3234080726"}]I want to use a function to convert the data size to megabyte or gigabyte like this;
if (size > 1073741823):return('{:.2f}'.format(size/(1024*1024*1024)), 'GB')
else:return('{:.2f}'.format(size/(1024*1024)), 'MB')I know the exact function might not work with my code. So where and how to use it so that I can get size output in gigabytes or megabytes. And if there is any easier way to achieve this then please tell.
Thank you and have a nice day.
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'
def humanbytes(B):
"""Return the given bytes as a human friendly KB, MB, GB, or TB string."""
B = float(B)
KB = float(1024)
MB = float(KB ** 2) # 1,048,576
GB = float(KB ** 3) # 1,073,741,824
TB = float(KB ** 4) # 1,099,511,627,776
if B < KB:
return '{0} {1}'.format(B,'Bytes' if 0 == B > 1 else 'Byte')
elif KB <= B < MB:
return '{0:.2f} KB'.format(B / KB)
elif MB <= B < GB:
return '{0:.2f} MB'.format(B / MB)
elif GB <= B < TB:
return '{0:.2f} GB'.format(B / GB)
elif TB <= B:
return '{0:.2f} TB'.format(B / TB)
tests = [1, 1024, 500000, 1048576, 50000000, 1073741824, 5000000000, 1099511627776, 5000000000000]
for t in tests: print("{0} == {1}".format(t,humanbytes(t)))
Output:
1 == 1.0 Byte
1024 == 1.00 KB
500000 == 488.28 KB
1048576 == 1.00 MB
50000000 == 47.68 MB
1073741824 == 1.00 GB
5000000000 == 4.66 GB
1099511627776 == 1.00 TB
5000000000000 == 4.55 TB
and for future me here it is in Perl too:
sub humanbytes {
my $B = shift;
my $KB = 1024;
my
KB ** 2; # 1,048,576
my
KB ** 3; # 1,073,741,824
my
KB ** 4; # 1,099,511,627,776
if (
KB) {
return "$B " . ((
B > 1) ? 'Bytes' : 'Byte');
} elsif (
KB &&
MB) {
return sprintf('%0.02f',
KB) . ' KB';
} elsif (
MB &&
GB) {
return sprintf('%0.02f',
MB) . ' MB';
} elsif (
GB &&
TB) {
return sprintf('%0.02f',
GB) . ' GB';
} elsif (
TB) {
return sprintf('%0.02f',
TB) . ' TB';
}
}
» pip install bitmath