Like Us Like Us Facebook Subscribe Subscribe us YouTube Whatsapp Share us Whatsapp Query Send your queries

Get Folder Size in Python: Easy Code Examples | Codentricks

Get Folder Size in Python: Easy Code Examples | Codentricks

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.

Get Folder Size in Python

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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments