DEV Community

Free Python Code
Free Python Code

Posted on

How to make human-readable file size in Python

Hi 🙂🖐

In this post, I will show you how to make human-readable file size
like: MB, KB, GB

I will use a Python library called human-readable

install

pip install human-readable
Enter fullscreen mode Exit fullscreen mode

create any file to test in this code I created a text file to text

from human_readable.files import file_size
import os

print(file_size(value = os.stat('test.txt').st_size))

Enter fullscreen mode Exit fullscreen mode

In this code, I used stat function to get information about my file
you can get many of the data you want but in this code. what I want to get file size only.

file_size function takes the size of the file and converts it to a human-readable size.

result

495.0 Bytes
Enter fullscreen mode Exit fullscreen mode

Top comments (0)