Tutorialspoint

How to calculate a directory size using Python?

How do I calculate a directory size in Python?



1 Answer
Rajendra Dharmkar

To get the size of a directory, you'll have to walk the whole directory tree and add size of each file. To do this you can use the os.walk() and os.path.getsize() functions. For example,

import os
total_size = 0
start_path = '.'  # To get size of current directory
for path, dirs, files in os.walk(start_path):
    for f in files:
        fp = os.path.join(path, f)
        total_size += os.path.getsize(fp)
print("Directory size: " + str(total_size))

If you're on *NIX OSes then you could simply call the du command using subprocess module as it is much easier than the way above. For example,

import subprocess
path = '.'
size = subprocess.check_output(['du','-sh', path]).split()[0].decode('utf-8')
print("Directory size: " + size)

Running either program will give the output:

Directory size: 1524664
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.