Convert file size to human readable text in Python

This Python tutorial we learn how to use the humanize package to convert file size from a number of bytes into human readable format string.

Install humanize package

Installing the humanize package using the following command.

pip install humanize

Convert file size into human readable string

To convert file size in number of bytes into readable string such as K, KiB, MB, GB we can use the naturalsize() method of humanize package as below.

import humanize

file_size1 = humanize.naturalsize(3000000)
file_size2 = humanize.naturalsize(300, binary=False, gnu=True)
file_size3 = humanize.naturalsize(3000, binary=False, gnu=True)
file_size4 = humanize.naturalsize(3000, binary=False, gnu=True, format='%.3f')
file_size5 = humanize.naturalsize(3000, binary=True)

print(file_size1)
print(file_size2)
print(file_size3)
print(file_size4)
print(file_size5)
The program output.
3.0 MB
300B
2.9K
2.930K
2.9 KiB

Happy Coding 😊