How to Create a File and Folder in Python

Today, I want to share a cool little Python project I worked on. It’s something simple but super useful a script that counts files and directories in any given folder on my computer. But that’s just the beginning i didn’t stop there. I enhanced it to filter files by extension, show the total size, and even list the largest files. If you’re someone who deals with a lot of files downloads folder chaos, this project can help you keep things tidy and informed.

Explanation of the Original Code

import os

This imports Python built in os module my go-to tool for working with the file system.

PATH = r'C:\Users\IRAWEN\Downloads\1050'

This is the target folder I wanted to scan.

  • Notice the r before the string that makes it a raw string, so I don’t have to double every backslash.

files, dirs = 0, 0

Just two simple counters to keep track of:

  • files: total number of files
  • dirs: total number of directories

The loop that does the heavy lifting:

for root, dirnames, filenames in os.walk(PATH):
print('Looking in:', root)
dirs += len(dirnames)
files += len(filenames)

Here’s what’s happening:

  • os.walk() recursively walks through every folder in the given path.
  • root: current directory being scanned
  • dirnames: list of sub-directories
  • filenames: list of files in the current directory

I print each folder I’m checking, and keep adding to the file and folder counters.

And finally the summary:

print('Files:', files)
print('Directories:', dirs)
print('Total:', files + dirs)

Simple and clean but i wanted more.

Now, Let Add More Practical Functionalities

Here are the features I added:

  1. List all file names
  2. Filter files by extension (e.g., .txt)
  3. Show total file size
  4. List the top 5 largest files

Here’s the full upgraded script:

Update & Enhance Code

import os

# Specify the path to count files and directories
PATH = r'C:\Users\IRAWEN\Downloads\1050'

files, dirs = 0, 0
total_size = 0
file_details = []

print(f"Scanning path: {PATH}\n")

for root, dirnames, filenames in os.walk(PATH):
print('Looking in:', root)
dirs += len(dirnames)
files += len(filenames)

for file in filenames:
file_path = os.path.join(root, file)
try:
size = os.path.getsize(file_path)
total_size += size
file_details.append((file, size))
except FileNotFoundError:
print(f"Warning: Skipped file (not found): {file_path}")

# Output
print('\nSummary:')
print('Files:', files)
print('Directories:', dirs)
print('Total items:', files + dirs)
print(f'Total file size: {total_size / (1024*1024):.2f} MB')

# Filter example: only .txt files
txt_files = [f for f in file_details if f[0].endswith('.txt')]
print(f'\nFound {len(txt_files)} .txt files:')
for name, size in txt_files:
print(f' {name} - {size / 1024:.2f} KB')

# Show largest files
print("\nTop 5 largest files:")
largest_files = sorted(file_details, key=lambda x: x[1], reverse=True)[:5]
for name, size in largest_files:
print(f' {name} - {size / (1024*1024):.2f} MB')

What You Can Learn from This

This small project touches on many real-world Python skills:

  • Navigating the file system
  • Exception handling (FileNotFoundError)
  • Working with file sizes
  • Filtering and sorting data
  • Formatting output for readability

Final Thought

This project was a great reminder of how powerful even simple Python scripts can be. By combining just a few functions from the os module, I was able to quickly analyze and organize my files, get insights into storage usage, and identify large or unnecessary items. It’s a practical tool that anyone can build and customize whether you’re managing downloads, cleaning up clutter, or just learning to work with file systems. Sometimes, the best way to grow your coding skills is to solve everyday problems like this one.

Related blog posts