Python Forum

Full Version: Convert file sizes: will this produce accurate results?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

Any suggestions on how to improve this script would be awesome.


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)))
    power = math.pow(1024, i) 
    size = round(size_bytes / power, 2) 
    return "%s %s" % (size, size_name[i])
Your function looks nice.

There is no much space for improvement.
You can use the newer string formatting syntax.

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)))
    power = math.pow(1024, i) 
    size = round(size_bytes / power, 2) 
    return "{} {}".format(size, size_name[i])
RickyWilson Wrote:will this produce accurate results?
You can write a test,pytest is advisable.
Here also with a couple of 3.6 features,f-string and underscore numbers.
Added doc-string then help() will work.
import math
import pytest

@pytest.mark.parametrize(
    'size_bytes, expected', [
        (1024 , '1.0 KB'),
        (1_048_576, '1.0 MB'),
        (1_099_511_627_776, '1.0 TB'),
    ]
)

def test_convert_size(size_bytes, expected):
    '''Convert Bytes to Kilobytes,Megabytes,Gigabytes,Terabytes...'''
    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)))
    power = math.pow(1024, i)
    size = round(size_bytes / power, 2)
    assert f"{size} {size_name}" == expected
pytest will find function named test and run values in mark.parametrize()
Output:
E:\1py_div\dec λ pytest ============================= test session starts ============================= platform win32 -- Python 3.6.2, pytest-3.3.0, py-1.5.2, pluggy-0.6.0 rootdir: E:\1py_div\dec, inifile: collected 3 items byte_convert_test.py ...                                                 [100%] ========================== 3 passed in 0.12 seconds ===========================