Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,094 questions

40,775 answers

573 users

How to format bytes to kilobytes, megabytes, gigabytes and terabytes in Python

Learn & Practice SQL


4,669 views
asked Apr 22, 2016 by avibootz
edited Apr 23, 2016 by avibootz

1 Answer

0 votes
def format_bytes(bytes_num):
    sizes = [ "B", "KB", "MB", "GB", "TB" ]

    i = 0
    dblbyte = bytes_num

    while (i < len(sizes) and bytes_num >= 1024):
            dblbyte = bytes_num / 1024.0
            i = i + 1
            bytes_num = bytes_num / 1024

    return str(round(dblbyte, 2)) + " " + sizes[i]


print(format_bytes(9823453784599))
print(format_bytes(7124362542))
print(format_bytes(23746178))
print(format_bytes(1048576))
print(format_bytes(1024000))
print(format_bytes(873445))
print(format_bytes(1024))
print(format_bytes(978))
print(format_bytes(13))
print(format_bytes(0))


'''
run:

8.93 TB
6.64 GB
22.65 MB
1.0 MB
1000.0 KB
852.97 KB
1.0 KB
978 B
13 B
0 B

'''

 





answered Apr 22, 2016 by avibootz
edited May 15, 2022 by avibootz
...