find the size of a directory in python

To find the size of a directory in Python, we can use the os module. The basic idea is to recursively iterate over all the files and directories within the given directory and sum up the sizes of all the files. Here's a function that does that:

main.py
import os

def get_dir_size(dir_path):
    """Return the total size of the directory and all its contents, in bytes."""
    total = 0
    with os.scandir(dir_path) as it:
        for entry in it:
            if entry.is_file():
                total += entry.stat().st_size
            elif entry.is_dir():
                total += get_dir_size(entry.path)
    return total
374 chars
13 lines

This function takes a single argument dir_path, which is the path to the directory that we want to find the size of. We start by initializing a variable total to 0. We then use the os.scandir() function to iterate over all the entries in the directory. For each entry, we check if it's a file or a directory. If it's a file, we use the st_size attribute of its stat() object to get its size and add it to the total. If it's a directory, we recursively call get_dir_size() with its path and add the result to the total. Finally, we return the total size.

Here's an example of using this function:

main.py
dir_path = '/path/to/directory'
dir_size = get_dir_size(dir_path)
print(f"Directory size: {dir_size} bytes")
109 chars
4 lines

gistlibby LogSnag