How to calculate a directory’s size using Python?

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 use the pathlib’s glob method to get all entries in the file system from the root.

And then we can use the is_file method to check if each file is a file.

If it is, then we use the stat method to get the file size.

And we use the sum method to sum all the file sizes together.

For instance, we write:

from pathlib import Path

root_directory = Path('.')
s = sum(f.stat().st_size for f in root_directory.glob('**/*') if f.is_file())
print(s)

We set root_directory to the root path object.

Then we call root_directory.glob with '**/*' to get everything under root_directory.

And we filter out non-files with if f.is_file().

Then we get the size of each file with f.stat().st_size.

And we call sum to add the file sizes together.

Therefore, s is a number in bytes like 16629.

Conclusion

To calculate a directory’s size using Python, we can use the pathlib’s glob method to get all entries in the file system from the root.

And then we can use the is_file method to check if each file is a file.

If it is, then we use the stat method to get the file size.

And we use the sum method to sum all the file sizes together.