Ever needed to check how much disk space a folder is consuming? Whether you’re managing server storage, analyzing project directories, or building a file management tool, Python makes it easy to calculate folder sizes. In this guide, you’ll learn multiple methods to get folder sizes using Python’s built-in modules—no external libraries required.

Why Calculate Folder Size Programmatically?
Manually checking folder sizes via file explorers isn’t practical for automation tasks. With Python, you can:
- Monitor disk usage on servers.
- Clean up large temporary folders.
- Build custom file management utilities.
- Analyze storage trends over time.
Prerequisites
- Basic knowledge of Python.
- Python 3.x installed.
- A folder with files to test.
Get Folder Size in Python Code
# using python default module
import os, getpass
username = getpass.getuser()
def folderSize(path):
total_size = 0
for root, dirs, files in os.walk(path):
for name in files:
file_path = os.path.join(root, name)
if os.path.isfile(file_path):
total_size+=os.path.getsize(file_path)
return total_size
folderName="Trash"
path="/home/"+username+"/.local/share/Trash/files"
size=folderSize(path) # size in bytes
size=size / (1024*1024)
print(f"{folderName} folder size is {size:.0f}MB")
Save file name as trash.py
and run command given below in terminal from same directory
python ./trash.py
If you have and query or suggestion or need assistance then please contact me, I will reply to fix your problem, if you like our content then you can subscribe to our Youtube channel. If you want to hire me then reach us at our Fiverr.







