Get File Size in Python

There are many ways available in Python to get a file size. 

Using os.path.getsize

The os.path.getsize is native python function to get file size. It takes string file path as parameter and returns file size in bytes as int.

from os import path

filesize = path.getsize("myfile.txt")
print(filesize)

Using Pathlib Module

Pathlib module introduce in python in Python 3.4 version. This is a powerful module for working with files. It is possible to do all kind of file or IO related task using pathlib module. It is also possible to get file size using Pathlib module.

from pathlib import Path

path = Path('myfile.txt')
file_io = path.start()

print("Filesize is: ", file_io.st_size)

Display file size in KB, MB, GB, TB

By default all methods return file size in bytes. It is very good to work with this data to machine but it is very complex to understand by humans. That’s why it is necessary to convert file size in kb, mb, gb or tb. Here is an example of how to show file size in kb, mb, gb, tb.

# Human readable filesize funtion
def human_readable_size(size, decimal_places=2):
    for unit in ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']:
        if size < 1024.0 or unit == 'PiB':
            break
        size /= 1024.0
    return f"{size:.{decimal_places}f} {unit}"


# Usages
from os.path import getsize
filesize_bytes = getsize("myfile.txt")
print(human_readable_size(filesize_bytes))

#output
10.25kb

Published
Categorized as Python

Leave a comment

Your email address will not be published. Required fields are marked *