 Convert file sizes: will this produce accurate results? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Convert file sizes: will this produce accurate results? (/thread-6709.html) Convert file sizes: will this produce accurate results? - RickyWilson - Dec-04-2017 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]) RE: Convert file sizes: will this produce accurate results? - DeaD_EyE - Dec-04-2017 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]) RE: Convert file sizes: will this produce accurate results? - snippsat - Dec-04-2017 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}" == expectedpytest 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 ===========================