Let’s see how to get the size of a directory in python.

How to get the size of a Directory in Python:

The Python os package gives the flexibility to access the file/directory structure so that we can walk through each file in a directory and get the size of them.

  • os.walk() function takes the directory path as a parameter and it walks through the directory.
  • os.path.getsize() function takes the file name as a parameter and gives the size of it.

So the sum of each file size in a directory gives us the total size of the directory.

get_directory_size.py
import os
import sys

if __name__ == '__main__':
    try:
        directory = input("Enter the directory which you want to get the size : ")
    except IndexError:
        sys.exit("Invalid directory")

    dir_size = 0
    readable_sizes = {'B': 1,
                 'KB': float(1) / 1024,
                 'MB': float(1) / (1024 * 1024),
                 'GB': float(1) / (1024 * 1024 * 1024)
                      }
    for (path, dirs, files) in os.walk(directory):
        for file in files:
            filename = os.path.join(path, file)
            dir_size += os.path.getsize(filename)
    readable_sizes_list = [str(round(readable_sizes[key] * dir_size, 2)) + " " + key for key in readable_sizes]

    if dir_size == 0:
        print("File Empty")
    else:
        for units in sorted(readable_sizes_list)[::-1]:
            print("Folder Size: " + units)

Output:

Enter the directory which you want to get the size : C:\Users\cgoka\Desktop\mylibs
Folder Size: 733160003 B
Folder Size: 715976.57 KB
Folder Size: 699.2 MB
Folder Size: 0.68 GB

References:

Happy Learning 🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment