How to calculate a directory size using Python?

PythonServer Side ProgrammingProgramming

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
Published on 27-Dec-2017 07:26:02