How to get the size of a file in Python ?

Published: February 21, 2023

Tags: Python;

DMCA.com Protection Status

To get the size of a file in Python, there are multiple solutions:

Using getsize() method

You can also use the getsize() method in the os module to get the size of a file. This method takes a path or URL as an argument and returns its size in bytes. For example:

import os

file_size = os.getsize('filename.txt')

print(file_size)

output

585989

in Byte.

To convert Byte to KB for example

1 Byte = 0.001 KB (in decimal)

So to get the output in KB:

file_size = os.getsize('filename.txt') * 0.001 # in KB

using stat() method

To get the size of a file in Python, you can use the stat() method in the os module. This method returns a tuple containing the file size, along with other information such as its permissions and creation time. To get the file size, use the st_size attribute of this tuple. For example:

import os

file_info = os.stat('filename.txt')

file_size = file_info.st_size

print(file_size)

output

585989

Using pathlib module

Alternatively, you can use the pathlib module to get the size of a file. The Path object created by this module has a stat() method that returns an object containing information about the file, including its size. To get the file size, use the .stat().st_size attribute. For example:

from pathlib import Path

file_info = Path('filename.txt').stat()

file_size = file_info.st_size

print(file_size)

output

585989

Total size of files with a given extension

To get all file ending with .hdf a solution is to use glob()

import glob
import os

file_list = glob.glob('media/*.hdf')

then we can iterate over all files and get the total size:

tot_size = 0

for file in file_list:
    file_size = os.path.getsize(file) * 0.001 # in KB
    tot_size += file_size
    print( str( round(file_size,2)  ) + ' KB')

output

250728.912 KB

References

Links Site
getsize() docs.python.org
pathlib docs.python.org
Bytes to KB Conversion gbmb.org