Categories
Python Answers

How to calculate a directory’s size using Python?

Spread the love

Sometimes, we want to calculate a directory’s size using Python.

In this article, we’ll look at how to calculate a directory’s size using Python.

How to calculate a directory’s size using Python?

To calculate a directory’s size using Python, we can loop through each file in the directory and get a sum of their sizes.

For instance, we write

import os

def get_size(start_path = '.'):
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(start_path):
        for f in filenames:
            fp = os.path.join(dirpath, f)
            if not os.path.islink(fp):
                total_size += os.path.getsize(fp)
    return total_size

print(get_size(), 'bytes')

to call os.walk to get an iterator with the files in all child directories of start_path.

Then we loop through them with a for loop.

In it, we loop through the filenames returned.

Then we get the file paths with

fp = os.path.join(dirpath, f)

We check if the path is a symbolic link with islink.

If it’s not, then we get the file’s size with getsize and add the size in bytes to total_size.

Once we’re done, we return total_size in bytes.

Conclusion

To calculate a directory’s size using Python, we can loop through each file in the directory and get a sum of their sizes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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