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 Overflow
🌐
GitHub
github.com › Submissions › PyBy-Converter
GitHub - Submissions/PyBy-Converter: A very simple python script for converting bytes to MB, GB, TB · GitHub
A very simple python script for converting bytes to MB, GB, TB - Submissions/PyBy-Converter
Author   Submissions
🌐
GitHub
gist.github.com › shawnbutts › 3906915
bytes to to mb, gb, etc in python · GitHub
def bytesto(bytes, to, bsize=1024): a = {'k' : 1, 'm': 2, 'g' : 3, 't' : 4, 'p' : 5, 'e' : 6 } r = float(bytes) return bytes / (bsize ** a[to])
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-file-size-in-bytes-kb-mb-and-gb-using-python
Get File Size in Bytes, Kb, Mb, And Gb using Python - GeeksforGeeks
July 23, 2025 - import os file_path = 'example.txt' file_size_bytes = os.path.getsize(file_path) # Conversion to kilobytes, megabytes, and gigabytes file_size_kb = file_size_bytes / 1024 file_size_mb = file_size_kb / 1024 file_size_gb = file_size_mb / 1024 print(f"File Size (Bytes): {file_size_bytes} B") print(f"File Size (KB): {file_size_kb:.2f} KB") print(f"File Size (MB): {file_size_mb:.2f} MB") print(f"File Size (GB): {file_size_gb:.2f} GB") ... The os.stat() function can provide more detailed information about a file, including its size. This method allows for greater flexibility in extracting various file attributes. In this example, code utilizes Python's `os` module to gather information about the file 'example.txt', including its size in bytes.
🌐
Finxter
blog.finxter.com › 5-best-ways-to-convert-bytes-to-megabytes-and-gigabytes-in-python
5 Best Ways to Convert Bytes to Megabytes and Gigabytes in Python – Be on the Right Side of Change
February 23, 2024 - ... bytes = 1500000 conversions = [bytes / 2**x for x in (20, 30)] print(f'{bytes} bytes is {conversions[0]} MB and {conversions[1]} GB') ... This one-liner uses a list comprehension to perform the conversion using shifts in binary exponents (2^20 for MB and 2^30 for GB).
🌐
Reddit
reddit.com › r/learnpython › how to convert the data size?
r/learnpython on Reddit: How to convert the data size?
April 28, 2022 -

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_list

Everything 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.

Top answer
1 of 16
58

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'
2 of 16
45
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';
   }
}
Find elsewhere
🌐
Program Creek
programcreek.com › python
Python convert bytes
def convert_bytes(bytes): bytes = float(bytes) if bytes >= 1099511627776: size, srepr = bytes / 1099511627776, "TB" elif bytes >= 1073741824: size, srepr = bytes / 1073741824, "GB" elif bytes >= 1048576: size, srepr = bytes / 1048576, "MB" elif bytes >= 1024: size, srepr = bytes / 1024, "KB" else: size, srepr = bytes, " bytes" return "%d%s" % (math.ceil(size), srepr)
🌐
Dot Net Perls
dotnetperls.com › convert-python
Python - Convert Types - Dot Net Perls
September 20, 2024 - 100000, "bytes =", megabytes1, "megabytes") # 1024 kilobytes to megabytes. megabytes2 = kilobytes_to_megabytes( ... With the dictionary built-in, we can convert from a list of tuples (with keys, values) to a dictionary. Dict() is a useful built-in method. Some conversions in Python are ...
🌐
YouTube
youtube.com › codesolve
python convert bytes to megabytes - YouTube
Instantly Download or Run the code at https://codegive.com title: python tutorial: converting bytes to megabytesintroduction:in this tutorial, we will explo...
Published   March 29, 2024
Views   18
🌐
Know Program
knowprogram.com › home › python code to convert bytes to kb, mb, gb, & tb
Python Code to Convert Bytes to KB, MB, GB, & TB
October 18, 2022 - Here, we will develop a program to convert bytes into MegaBytes in Python programming language. One MegaByte (MB) is equal to 1024 KiloBytes, so one MB is equivalent to 1024 * 1024 bytes.
🌐
PyPI
pypi.org › project › formatbytes
Client Challenge
JavaScript is disabled in your browser · Please enable JavaScript to proceed · A required part of this site couldn’t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
🌐
Compucademy
compucademy.net › exploring-byte-to-gb-conversions-using-python
Exploring Byte to GB Conversions Using Python – Compucademy
def bytes_to_gb(bytes_val): return bytes_val / 1_000_000_000 def bytes_to_gib(bytes_val): return bytes_val / 1_073_741_824 def gb_to_bytes(gb_val): return gb_val * 1_000_000_000 def gib_to_bytes(gib_val): return gib_val * 1_073_741_824 def main(): while True: print("\nMenu:") print("1. Bytes to Gigabytes (GB)") print("2. Bytes to Gibibytes (GiB)") print("3. Gigabytes to Bytes") print("4. Gibibytes to Bytes") print("5. Exit") choice = input("Enter your choice (1-5): ") if choice == '1': bytes_val = float(input("Enter the amount in bytes: ")) print(f"{bytes_val} Bytes is equal to {bytes_to_gb(by
Price   $$
Address   United Kingdom
🌐
PyPI
pypi.org › project › bitmath › 1.0.2-3
bitmath · PyPI
March 16, 2014 - Thus, today, MB = 1000000B and MiB = 1048576B. In the free software world programs are slowly being changed to conform. When the Linux kernel boots and says ... “Once upon a time, computer professionals noticed that 210 was very nearly equal ...
      » pip install bitmath
    
Published   Mar 16, 2014
Version   1.0.2-3
🌐
Python Forum
python-forum.io › thread-24919.html
Create a bits & bytes conversion table
March 10, 2020 - Hiii! I am doing homework about converting bits, bytes, KB and so on. It works fine for me to convert the number but I am struggling with the bonus. This is the instruction: BEFORE or AFTER you print out the conversion table, print out the largest a...
🌐
Medium
medium.com › @ryan_forrester_ › getting-file-sizes-in-python-a-complete-guide-01293aaa68ef
Getting File Sizes in Python: A Complete Guide | by ryan | Medium
October 24, 2024 - def convert_size(size_bytes): """Convert bytes to human readable format.""" for unit in ['B', 'KB', 'MB', 'GB', 'TB']: if size_bytes < 1024: return f"{size_bytes:.2f} {unit}" size_bytes /= 1024 return f"{size_bytes:.2f} PB" # Usage file_size ...
🌐
Python
bugs.python.org › issue31749
Issue 31749: Request: Human readable byte amounts in the standard library - Python tracker
October 10, 2017 - This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/75930
🌐
ActiveState
code.activestate.com › recipes › 578019-bytes-to-human-human-to-bytes-converter
Bytes-to-human / human-to-bytes converter « Python recipes « ActiveState Code
Extra: for an alternative version as simple as possible (no global vars, no extra args, easier to customize) see here: http://code.google.com/p/pyftpdlib/source/browse/trunk/test/bench.py?spec=svn984&r=984#137 · Hi, How can I use this script from a linux shell? Thanks