How to get the size of a folder in Python?

In this tutorial, we will learn how to get the size of a folder in Python.

Let us first see some prerequisite required for this code. The OS module in Python enables us to interact with the operating system and perform various related tasks. This module is a predefined standard module of Python. os.path module is a submodule of the OS module. It contains various functions on pathnames or in simpler terms, used instead of long file names. To access this module, we use the syntax:

import os

Some functions of os.path we will need to solve this problem are:

  1. os.path.join() method joins different path components such as directories, sub directories, files, etc. Each component is separated by (\). Syntax: os.path.join(path)
  2. os.path.getsize() method returns the size of the file or directory in bytes. Syntax: os.path.getsize(path)

Another method that will be used is os.walk(). It walks the tree of directories either top-down or bottom-up and generates the file names. 3 tuples are yielded: dirpath, dirnames, filenames.

Python program to generate size of a folder

Problem statement: Write a Python program to get the size of a folder.

Steps/Algorithm: 

  1. Import the OS module.
  2. Define a function (size) and give the path of the folder or directory.
  3. Initialize the total size as 0.
  4. Navigate or walk through the directory tree using the os.walk() method.
  5. Join or concatenate all the components of the path using the os.path.join() function.
  6. Get the sizes of individual files in the directory and add it to the total size.
  7. Print the total size generated.

Program/Code:

import os
def size(path = 'C:\\Users\ADMIN\Documents\programs\Python'):
   
    #initialize the size
    total_size = 0
    
    #use the walk() method to navigate through directory tree
    for dirpath, dirnames, filenames in os.walk(path):
        for i in filenames:
            
            #use join to concatenate all the components of path
            f = os.path.join(dirpath, i)
            
            #use getsize to generate size in bytes and add it to the total size
            total_size += os.path.getsize(f)

    return total_size

print(size())

If we run our program then it will show the size of our given file in the Python program:

1246

I hope, you have understood how we can get the size of a complete folder with just a few lines of code.

Also, read:

 

Leave a Reply

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