Python Automatic Desktop Organizer
Sort 25 business files into folders automatically using Python dictionaries.
Introduction
30 Second Summary
Think about the last time you searched through a cluttered desktop full of scattered reports, invoices, and spreadsheets. Most office workers spend minutes every day just looking for the right file.
In this project, you will build an Automatic Desktop Organizer that creates 25 realistic business files and then sorts them into clean category folders using Python.
What You'll Build
An interactive Google Colab notebook that simulates a messy business desktop and automatically organizes 25 scattered files into categorized subfolders using a dictionary-based mapping system and the os/shutil modules.
By the end of this project, you'll have:
- A file simulation engine that creates 25 realistic business files in a messy folder using open() and for loops.
- A dictionary-based organizer that maps 8 file extensions to 5 folder categories and sorts files automatically using os.path.splitext(), os.makedirs(), and shutil.move().
- A sandbox-ready notebook published to GitHub with an Open in Colab badge that anyone can click to run without reading Python.
- Secret Mission: A file organization summary report with per-category counts, a text bar chart, and unknown file type detection.
Are there any prerequisites?
This is Day 3 of the Python for Business series. You should have completed Day 2 and have your python-portfolio GitHub repository ready from Day 1.
Set Up Your Day 3 Notebook
Today you are building an Automatic Desktop Organizer that sorts 25 messy business files into clean category folders using Python.
Before writing any code, you need a fresh notebook in Google Colab with a branded header and section markers so your notebook stays organized from the start.
In this step, get ready to:
- Create and rename your Day 3 notebook in Google Colab.
- Add a branded header listing the Python concepts you will learn.
- Add a section heading to organize your notebook structure.
Open Google Colab and create a new notebook
Google Colab is a free, browser-based Python environment that requires no installation. You will use it to write and run all of today's code.
- Open your browser and go to colab.research.google.com.
- Click New notebook to create a fresh notebook.
- Click the notebook title in the upper-left corner (it will say something like Untitled0.ipynb).
- Replace the name with Day_3_Automatic_Desktop_Organizer.ipynb and press Enter.
Why this naming convention?
Using underscores instead of spaces in filenames prevents issues with file paths in code. The Day_3_ prefix also keeps your notebooks sorted chronologically in your GitHub portfolio.
Add the branded markdown header
A branded header at the top of your notebook tells visitors what the project does and what Python concepts it covers.
- Delete the empty code cell that Colab creates by default. Click the cell, then click the trash icon that appears in the cell toolbar.
- Click + Text in the top-left toolbar to add a text cell.
- Paste the following markdown into the text cell:
# Day 3: The Automatic Desktop Organizer
**Python Concepts Covered:**
- Dictionaries (key-value mapping)
- For Loops (batch file processing)
- `os` Module (`makedirs`, `listdir`, `path.splitext`, `path.join`, `path.isfile`)
- `shutil` Module (`move`)
- String Methods (`.lower()`)
This tool simulates a cluttered business desktop and automatically organizes 25 scattered files into categorized folders using a dictionary-based mapping system.
What does this header do?
The # creates a large title heading. The bulleted list uses markdown formatting to preview every Python concept covered in the project.
When someone opens your notebook from GitHub, this header immediately tells them what the project does and what skills it demonstrates.
- Press Shift+Enter or click outside the cell to render the markdown.
- You should see a large "Day 3: The Automatic Desktop Organizer" heading, a bold "Python Concepts Covered:" label, five bulleted items, and a one-line project description.
Seeing raw markdown instead of formatted text?
Make sure you added a Text cell, not a Code cell. Code cells run Python and will not render markdown.
If you accidentally used a code cell, delete it and click + Text to create the correct cell type.
help me fix my Colab text cell not rendering markdown
Add the section heading text cell
Your notebook needs section headings to separate the simulation code from the organizer code. This heading tells visitors what the next code cell will do.
- Click + Text again to add another text cell below your header.
- Paste the following markdown into the new text cell:
## Messy Desktop Simulation
The next code cell generates 25 realistic business files in a single folder to simulate a cluttered desktop. Click the play button to create the mess, then watch the organizer sort it.
What does this cell do?
The ## creates a smaller subheading. This text acts as a signpost for anyone clicking through your notebook. They know the next play button will generate files without needing to read any code.
- Press Shift+Enter or click outside the cell to render it.
- You should see a "Messy Desktop Simulation" subheading followed by a short description paragraph.
- Save your notebook by pressing Ctrl+S (Windows) or Cmd+S (macOS).
Not sure if the notebook saved?
Look at the notebook title in the upper-left corner. If it shows a checkmark or says "All changes saved", your work is saved to Google Drive automatically.
help me confirm my Colab notebook saved correctly
✔️ Awesome, I've got everything!
Great. Double check that your notebook is named Day_3_Automatic_Desktop_Organizer.ipynb and that both text cells are rendered (not in edit mode).
ⓧ I'd like to double check the full code
Here is the complete content for both text cells. Make sure yours matches:
Text Cell 1 (branded header):
# Day 3: The Automatic Desktop Organizer
**Python Concepts Covered:**
- Dictionaries (key-value mapping)
- For Loops (batch file processing)
- `os` Module (`makedirs`, `listdir`, `path.splitext`, `path.join`, `path.isfile`)
- `shutil` Module (`move`)
- String Methods (`.lower()`)
This tool simulates a cluttered business desktop and automatically organizes 25 scattered files into categorized folders using a dictionary-based mapping system.
Text Cell 2 (section heading):
## Messy Desktop Simulation
The next code cell generates 25 realistic business files in a single folder to simulate a cluttered desktop. Click the play button to create the mess, then watch the organizer sort it.
Your notebook is set up and ready to go. Next, you will write the code that simulates a messy desktop full of 25 scattered business files.
Simulate a Messy Desktop with 25 Business Files
Your notebook has a branded header and a section heading ready to go. Now it's time to write actual Python code that does real work.
Before you can organize files, you need files to organize. In this step, you'll create a code cell that generates 25 realistic business files in a single folder to simulate the chaos of a cluttered desktop.
In this step, get ready to:
- Write a code cell that creates 25 business files inside a simulated messy desktop folder.
- Display a formatted "before" snapshot showing all 25 files as a flat, unorganized list.
- Run the cell and confirm all 25 files appear in the output.
Write the file simulation code
Python's os module gives you tools for working with the file system. You'll use it to create a folder and generate empty files that represent a real business desktop.
- In your notebook, click + Code in the toolbar to add a new code cell below your "Messy Desktop Simulation" text cell.
- Paste the following code into the new code cell:
#@title Simulate a Messy Desktop
#@markdown Click the play button to create 25 business files.
import os
# Create the messy desktop folder
desktop_path = "/content/messy_desktop"
os.makedirs(desktop_path, exist_ok=True)
# 25 realistic business files
business_files = [
"Q1_Revenue_Report.pdf",
"Client_Invoice_042.pdf",
"Annual_Budget_Summary.pdf",
"Employee_Handbook.pdf",
"Meeting_Minutes_June.pdf",
"Marketing_Budget_2025.xlsx",
"Sales_Forecast_Q2.xlsx",
"Inventory_Tracker.xlsx",
"Client_Contact_List.csv",
"Expense_Report_May.csv",
"Team_Photo_Retreat.png",
"Product_Screenshot.png",
"Office_Floor_Plan.png",
"Company_Logo_Final.jpg",
"Event_Banner_Draft.jpg",
"Board_Meeting_Deck.pptx",
"Sales_Pitch_ClientX.pptx",
"Onboarding_Training.pptx",
"Project_Proposal_Draft.docx",
"Contract_Template.docx",
"Weekly_Status_Update.docx",
"Vendor_Agreement.docx",
"Quick_Notes.txt",
"Password_Reset_Instructions.txt",
"Server_Maintenance_Log.txt",
]
# Create all 25 files
for filename in business_files:
filepath = os.path.join(desktop_path, filename)
open(filepath, "w").close()
What does this code do?
- #@title and #@markdown are Colab directives that hide the code and show a clickable title. Visitors will see a play button and label, not raw Python.
- os.makedirs(desktop_path, exist_ok=True) creates the /content/messy_desktop folder. The exist_ok=True flag prevents errors if the folder already exists.
- business_files is a list of 25 realistic filenames with different extensions (.pdf, .xlsx, .csv, .png, .jpg, .pptx, .docx, .txt).
- The for loop iterates through each filename and creates an empty file using open(filepath, "w").close(). The "w" mode creates the file if it doesn't exist.
You won't see any output yet. The next chunk adds the display that prints the file listing.
Add the "before" snapshot display
Creating files silently isn't very satisfying. You need a visual printout that proves all 25 files now exist in one chaotic, unorganized pile.
- In the same code cell, add the following code directly below the open(filepath, "w").close() line:
print(f"Created {len(business_files)} files in {desktop_path}")
print()
# Display the "before" snapshot
print(f"{'=' * 50}")
print(f" MESSY DESKTOP - BEFORE ORGANIZING")
print(f"{'=' * 50}")
print()
files = sorted(os.listdir(desktop_path))
for f in files:
print(f" {f}")
print()
print(f"Total files: {len(files)}")
print(f"{'=' * 50}")
What does this display code do?
- os.listdir(desktop_path) returns a list of every file in the messy desktop folder.
- sorted() alphabetizes the list so the output is consistent every time you run it.
- The formatted header with {'=' * 50} prints a row of 50 equals signs to frame the output like a report. This is the "before" view that you'll compare against the organized "after" view later.
- Click the play button (triangle icon) to the left of the code cell to run it.
- You should see "Created 25 files in /content/messy_desktop" followed by a formatted box listing all 25 filenames alphabetically, ending with "Total files: 25".
Why does #@title matter for sharing?
When someone opens your notebook from the Open in Colab badge, the #@title directive collapses the code by default. Visitors see only a "Simulate a Messy Desktop" header with a play button.
They can click play and see the output without reading a single line of Python. This turns your notebook into a sandbox-style app.
Not seeing 25 files in the output?
- Check that the entire code is in one cell. If you accidentally split it across two cells, the second half won't have access to business_files or desktop_path.
- Make sure there's no indentation error on the for loop. The for filename in business_files: line should have no leading spaces.
- If you see "NameError: name 'os' is not defined", the import os line at the top of the cell may be missing.
Help me debug my messy desktop simulation cell
✔️ Awesome, I've got everything!
Great. Double check you see all 25 files listed and "Total files: 25" at the bottom of the output.
ⓧ I'd like to double check the full code
Here's the complete code that should be in your first code cell:
#@title Simulate a Messy Desktop
#@markdown Click the play button to create 25 business files.
import os
# Create the messy desktop folder
desktop_path = "/content/messy_desktop"
os.makedirs(desktop_path, exist_ok=True)
# 25 realistic business files
business_files = [
"Q1_Revenue_Report.pdf",
"Client_Invoice_042.pdf",
"Annual_Budget_Summary.pdf",
"Employee_Handbook.pdf",
"Meeting_Minutes_June.pdf",
"Marketing_Budget_2025.xlsx",
"Sales_Forecast_Q2.xlsx",
"Inventory_Tracker.xlsx",
"Client_Contact_List.csv",
"Expense_Report_May.csv",
"Team_Photo_Retreat.png",
"Product_Screenshot.png",
"Office_Floor_Plan.png",
"Company_Logo_Final.jpg",
"Event_Banner_Draft.jpg",
"Board_Meeting_Deck.pptx",
"Sales_Pitch_ClientX.pptx",
"Onboarding_Training.pptx",
"Project_Proposal_Draft.docx",
"Contract_Template.docx",
"Weekly_Status_Update.docx",
"Vendor_Agreement.docx",
"Quick_Notes.txt",
"Password_Reset_Instructions.txt",
"Server_Maintenance_Log.txt",
]
# Create all 25 files
for filename in business_files:
filepath = os.path.join(desktop_path, filename)
open(filepath, "w").close()
print(f"Created {len(business_files)} files in {desktop_path}")
print()
# Display the "before" snapshot
print(f"{'=' * 50}")
print(f" MESSY DESKTOP - BEFORE ORGANIZING")
print(f"{'=' * 50}")
print()
files = sorted(os.listdir(desktop_path))
for f in files:
print(f" {f}")
print()
print(f"Total files: {len(files)}")
print(f"{'=' * 50}")
You now have a simulated cluttered desktop with 25 files dumped in one flat folder. Next up, you'll build the organizer engine that sorts all of these files into clean, categorized subfolders automatically.
Build and Run the File Organizer Engine
Your messy desktop has 25 scattered files with no structure. Manually sorting these into folders would take time, and you would have to repeat the work every time new files pile up.
In this step, you will build the organizer engine that reads each file's extension, looks up which category it belongs to, and moves it into the correct folder automatically. The entire system runs in a single click.
In this step, get ready to:
- Build a dictionary-based file organizer that sorts 25 files into 5 category folders.
- Run the organizer and confirm all files are moved.
- Display a formatted directory tree showing the clean organized structure.
Create the organizer code cell
The organizer needs to know which file extensions belong to which folder. A dictionary maps each extension to a category name, so the organizer can look up any extension instantly without a long chain of if/elif statements.
- Click + Code in the toolbar to add a new code cell below your existing cell.
- Paste the following code into the new cell to set up the organizer's category map:
#@title Run the Automatic Desktop Organizer
#@markdown Click play to sort all 25 files into categorized folders.
import shutil
# Dictionary mapping file extensions to folder categories
file_categories = {
".pdf": "Reports",
".xlsx": "Spreadsheets",
".csv": "Spreadsheets",
".png": "Images",
".jpg": "Images",
".pptx": "Presentations",
".docx": "Documents",
".txt": "Documents",
}
What is a dictionary?
A dictionary stores key-value pairs. Here, each key is a file extension (like .pdf) and each value is the folder name it belongs to (like Reports). Looking up an extension in the dictionary instantly returns its category.
Notice that multiple extensions can map to the same folder. Both .xlsx and .csv map to Spreadsheets because they serve the same purpose.
Why a dictionary instead of if/elif/else?
In Day 2, you used if/elif/else to handle 3 pricing tiers. That worked fine for a small number of conditions. With 8 extensions across 5 categories, if/elif/else would become long and repetitive.
A dictionary does the same routing in a single data structure. Adding a new extension later means adding one line to the dictionary instead of inserting another elif block.
Now add the for loop that processes each file, looks up its category, and moves it to the right folder.
- In the same code cell, paste this code below the dictionary to complete the organizer engine:
# Organize files into category folders
files_moved = 0
for filename in os.listdir(desktop_path):
filepath = os.path.join(desktop_path, filename)
# Skip directories - only process files
if not os.path.isfile(filepath):
continue
# Get the file extension (lowercase for consistent matching)
name, extension = os.path.splitext(filename)
extension = extension.lower()
# Look up the category in the dictionary
if extension in file_categories:
category = file_categories[extension]
else:
category = "Other"
# Create the category folder if it doesn't exist
category_path = os.path.join(desktop_path, category)
os.makedirs(category_path, exist_ok=True)
# Move the file into the category folder
destination = os.path.join(category_path, filename)
shutil.move(filepath, destination)
files_moved += 1
print(f"Organizing complete! Moved {files_moved} files.")
What does this code do?
The for loop iterates through every item in the messy desktop folder. For each file, it:
- os.path.isfile() checks if the item is a file (not a subfolder). If it is a subfolder, continue skips to the next item.
- os.path.splitext() splits the filename into its name and extension (e.g., "report.pdf" becomes ("report", ".pdf")).
- .lower() converts the extension to lowercase so .PDF and .pdf both match.
- shutil.move() physically relocates the file from the flat folder into its category subfolder.
- files_moved += 1 counts each successful move so you see the total at the end.
- Click the play button (or press Shift+Enter) to run the cell.
- You should see: Organizing complete! Moved 25 files.
Seeing 0 files moved?
If the output says 0 files moved, it means the files are already organized from a previous run. Go back to Code Cell 1 (Simulate a Messy Desktop) and re-run it first to recreate the flat file list. Then run this cell again.
Help me figure out why my organizer moved 0 files.
✔️ Awesome, I've got everything!
Great. Double check you see the success message confirming 25 files were moved.
ⓧ I'd like to double check the full code
Here is the complete Code Cell 2. Make sure your cell matches this exactly:
#@title Run the Automatic Desktop Organizer
#@markdown Click play to sort all 25 files into categorized folders.
import shutil
file_categories = {
".pdf": "Reports",
".xlsx": "Spreadsheets",
".csv": "Spreadsheets",
".png": "Images",
".jpg": "Images",
".pptx": "Presentations",
".docx": "Documents",
".txt": "Documents",
}
files_moved = 0
for filename in os.listdir(desktop_path):
filepath = os.path.join(desktop_path, filename)
if not os.path.isfile(filepath):
continue
name, extension = os.path.splitext(filename)
extension = extension.lower()
if extension in file_categories:
category = file_categories[extension]
else:
category = "Other"
category_path = os.path.join(desktop_path, category)
os.makedirs(category_path, exist_ok=True)
destination = os.path.join(category_path, filename)
shutil.move(filepath, destination)
files_moved += 1
print(f"Organizing complete! Moved {files_moved} files.")
Display the organized folder structure
The files are now sorted, but you need a way to see the results. This next cell prints a formatted directory tree showing each category folder and its contents.
- Click + Code to add another new code cell below.
- Paste the following code to create the "after" display:
#@title View Your Organized Desktop
#@markdown Click play to see the clean folder structure.
print(f"{'=' * 50}")
print(f" ORGANIZED DESKTOP - AFTER")
print(f"{'=' * 50}")
print()
for folder_name in sorted(os.listdir(desktop_path)):
folder_path = os.path.join(desktop_path, folder_name)
if os.path.isdir(folder_path):
folder_files = sorted(os.listdir(folder_path))
print(f" {folder_name}/ ({len(folder_files)} files)")
for f in folder_files:
print(f" {f}")
print()
print(f"{'=' * 50}")
print(f"Desktop organized successfully!")
print(f"{'=' * 50}")
What does this code do?
- os.listdir(desktop_path) lists everything in the messy_desktop folder (which is now subfolders, not flat files).
- os.path.isdir() filters to only show directories (your category folders), skipping anything else.
- For each folder, it lists and counts the files inside, printing an indented tree view.
- Click the play button (or press Shift+Enter) to run the cell.
- You should see 5 category folders (Documents, Images, Presentations, Reports, Spreadsheets) with files listed beneath each one.
Seeing an empty output?
If no folders appear, it means Code Cell 2 did not run successfully. Check that you ran the organizer cell first and saw the "Organizing complete" message. If the organizer ran but this cell still shows nothing, make sure you are referencing desktop_path (not a hardcoded string with a typo).
Help me debug why my organized desktop display is empty.
✔️ Awesome, I've got everything!
Great. You should see all 25 files neatly distributed across the 5 category folders.
ⓧ I'd like to double check the full code
Here is the complete Code Cell 3. Make sure your cell matches this exactly:
#@title View Your Organized Desktop
#@markdown Click play to see the clean folder structure.
print(f"{'=' * 50}")
print(f" ORGANIZED DESKTOP - AFTER")
print(f"{'=' * 50}")
print()
for folder_name in sorted(os.listdir(desktop_path)):
folder_path = os.path.join(desktop_path, folder_name)
if os.path.isdir(folder_path):
folder_files = sorted(os.listdir(folder_path))
print(f" {folder_name}/ ({len(folder_files)} files)")
for f in folder_files:
print(f" {f}")
print()
print(f"{'=' * 50}")
print(f"Desktop organized successfully!")
print(f"{'=' * 50}")
Your organizer works. 25 chaotic files are now sorted into 5 clean folders with zero manual effort. Next up, you will add documentation and publish this notebook to GitHub so anyone can run it.
Add Documentation and Publish to GitHub
Your organizer works. It creates 25 files and sorts them into 5 tidy folders in seconds.
Working code without documentation is hard to revisit. In this step, you will add explanation cells so anyone reading your notebook understands how the code works, then publish the notebook to your GitHub portfolio so you can share it anywhere.
In this step, get ready to:
- Add a "How This Code Works" documentation cell explaining each Python technique.
- Add a "Key Takeaways and Next Steps" summary cell.
- Publish the notebook to GitHub and add an Open in Colab badge.
Add the "How This Code Works" text cell
Documentation cells explain the "why" behind your code. Visitors who click your Open in Colab badge can read these cells without digging into the Python.
- Click the + Text button that appears between Code Cell 3 and the bottom of the notebook.
- Paste the following markdown into the new text cell:
## How This Code Works
- **Dictionaries** map file extensions to folder category names, providing instant key-value lookups without chains of if/elif statements.
- **For Loops** iterate through every file in the messy desktop folder, processing each one automatically.
- **`os.path.splitext()`** splits a filename into its name and extension (e.g., `"report.pdf"` becomes `("report", ".pdf")`).
- **`os.makedirs(exist_ok=True)`** creates destination folders only when they don't already exist, preventing errors on repeat runs.
- **`shutil.move()`** physically relocates files from the flat folder into their categorized subfolders.
- **`os.path.isfile()`** checks whether a path points to a file (not a folder), so the loop skips directories.
- **`.lower()`** converts extensions to lowercase for case-insensitive matching (handles .PDF, .Xlsx, etc.).
What does this cell do?
Each bullet explains one Python technique used in the organizer. Together they form a quick-reference cheat sheet for the reader.
Notice how the cell references real examples (like "report.pdf" splitting into a tuple). Concrete examples make documentation easier to scan than abstract definitions.
- Click outside the text cell and confirm it renders with bold technique names and inline code formatting.
Text cell showing raw markdown characters?
Click outside the text cell to exit edit mode. Colab renders markdown only when the cell is not selected for editing.
If bold or code formatting still looks wrong, check that every ** pair is closed and backticks are not nested inside bold markers.
help me fix my markdown formatting in Colab
Add the "Key Takeaways and Next Steps" text cell
A takeaways cell gives readers (and future-you) a quick summary of what was built and what skills it used.
- Click the + Text button below the "How This Code Works" cell you just created.
- Paste the following markdown into the new text cell:
## Key Takeaways and Next Steps
**What I built today:**
An Automatic Desktop Organizer that generates 25 business files and sorts them into 5 categorized folders using a dictionary-based extension mapping system.
**Python skills I used:**
- Dictionaries for key-value data mapping
- For loops for batch processing files
- `os` module (`makedirs`, `listdir`, `path.splitext`, `path.join`, `path.isfile`)
- `shutil.move()` to relocate files programmatically
- `.lower()` for case-insensitive string comparison
**Next up (Day 4):**
Building on loops and dictionaries to process structured business data.
What does this cell do?
The cell acts as a project reflection. It names the finished product, lists the skills practiced, and teases Day 4 so you have a natural continuation point.
Anyone visiting your portfolio sees a clear summary of what you accomplished without scrolling through code.
- Click outside the cell and confirm it renders with bold headings and a bulleted skills list.
Cell renders but looks cramped?
Ensure you have a blank line between the bold heading line (e.g. **What I built today:**) and the paragraph beneath it. Markdown needs blank lines to separate blocks.
help me fix spacing in my Colab markdown cell
✔️ Awesome, I've got everything!
Great. Make sure both text cells render correctly with formatted headings, bold text, and bullet points before moving on to publishing.
ⓧ I'd like to double check the full code
Here is the complete notebook content including all text cells and code cells up to this point:
# Day 3: The Automatic Desktop Organizer
**Python Concepts Covered:**
- Dictionaries (key-value mapping)
- For Loops (batch file processing)
- `os` Module (`makedirs`, `listdir`, `path.splitext`, `path.join`, `path.isfile`)
- `shutil` Module (`move`)
- String Methods (`.lower()`)
This tool simulates a cluttered business desktop and automatically organizes 25 scattered files into categorized folders using a dictionary-based mapping system.
## Messy Desktop Simulation
The next code cell generates 25 realistic business files in a single folder to simulate a cluttered desktop. Click the play button to create the mess, then watch the organizer sort it.
#@title Simulate a Messy Desktop
#@markdown Click the play button to create 25 business files.
import os
# Create the messy desktop folder
desktop_path = "/content/messy_desktop"
os.makedirs(desktop_path, exist_ok=True)
# 25 realistic business files
business_files = [
"Q1_Revenue_Report.pdf",
"Client_Invoice_042.pdf",
"Annual_Budget_Summary.pdf",
"Employee_Handbook.pdf",
"Meeting_Minutes_June.pdf",
"Marketing_Budget_2025.xlsx",
"Sales_Forecast_Q2.xlsx",
"Inventory_Tracker.xlsx",
"Client_Contact_List.csv",
"Expense_Report_May.csv",
"Team_Photo_Retreat.png",
"Product_Screenshot.png",
"Office_Floor_Plan.png",
"Company_Logo_Final.jpg",
"Event_Banner_Draft.jpg",
"Board_Meeting_Deck.pptx",
"Sales_Pitch_ClientX.pptx",
"Onboarding_Training.pptx",
"Project_Proposal_Draft.docx",
"Contract_Template.docx",
"Weekly_Status_Update.docx",
"Vendor_Agreement.docx",
"Quick_Notes.txt",
"Password_Reset_Instructions.txt",
"Server_Maintenance_Log.txt",
]
# Create all 25 files
for filename in business_files:
filepath = os.path.join(desktop_path, filename)
open(filepath, "w").close()
print(f"Created {len(business_files)} files in {desktop_path}")
print()
# Display the "before" snapshot
print(f"{'=' * 50}")
print(f" MESSY DESKTOP - BEFORE ORGANIZING")
print(f"{'=' * 50}")
print()
files = sorted(os.listdir(desktop_path))
for f in files:
print(f" {f}")
print()
print(f"Total files: {len(files)}")
print(f"{'=' * 50}")
#@title Run the Automatic Desktop Organizer
#@markdown Click play to sort all 25 files into categorized folders.
import shutil
# Dictionary mapping file extensions to folder categories
file_categories = {
".pdf": "Reports",
".xlsx": "Spreadsheets",
".csv": "Spreadsheets",
".png": "Images",
".jpg": "Images",
".pptx": "Presentations",
".docx": "Documents",
".txt": "Documents",
}
# Organize files into category folders
files_moved = 0
for filename in os.listdir(desktop_path):
filepath = os.path.join(desktop_path, filename)
# Skip directories - only process files
if not os.path.isfile(filepath):
continue
# Get the file extension (lowercase for consistent matching)
name, extension = os.path.splitext(filename)
extension = extension.lower()
# Look up the category in the dictionary
if extension in file_categories:
category = file_categories[extension]
else:
category = "Other"
# Create the category folder if it doesn't exist
category_path = os.path.join(desktop_path, category)
os.makedirs(category_path, exist_ok=True)
# Move the file into the category folder
destination = os.path.join(category_path, filename)
shutil.move(filepath, destination)
files_moved += 1
print(f"Organizing complete! Moved {files_moved} files.")
#@title View Your Organized Desktop
#@markdown Click play to see the clean folder structure.
print(f"{'=' * 50}")
print(f" ORGANIZED DESKTOP - AFTER")
print(f"{'=' * 50}")
print()
for folder_name in sorted(os.listdir(desktop_path)):
folder_path = os.path.join(desktop_path, folder_name)
if os.path.isdir(folder_path):
folder_files = sorted(os.listdir(folder_path))
print(f" {folder_name}/ ({len(folder_files)} files)")
for f in folder_files:
print(f" {f}")
print()
print(f"{'=' * 50}")
print(f"Desktop organized successfully!")
print(f"{'=' * 50}")
## How This Code Works
- **Dictionaries** map file extensions to folder category names, providing instant key-value lookups without chains of if/elif statements.
- **For Loops** iterate through every file in the messy desktop folder, processing each one automatically.
- **`os.path.splitext()`** splits a filename into its name and extension (e.g., `"report.pdf"` becomes `("report", ".pdf")`).
- **`os.makedirs(exist_ok=True)`** creates destination folders only when they don't already exist, preventing errors on repeat runs.
- **`shutil.move()`** physically relocates files from the flat folder into their categorized subfolders.
- **`os.path.isfile()`** checks whether a path points to a file (not a folder), so the loop skips directories.
- **`.lower()`** converts extensions to lowercase for case-insensitive matching (handles .PDF, .Xlsx, etc.).
## Key Takeaways and Next Steps
**What I built today:**
An Automatic Desktop Organizer that generates 25 business files and sorts them into 5 categorized folders using a dictionary-based extension mapping system.
**Python skills I used:**
- Dictionaries for key-value data mapping
- For loops for batch processing files
- `os` module (`makedirs`, `listdir`, `path.splitext`, `path.join`, `path.isfile`)
- `shutil.move()` to relocate files programmatically
- `.lower()` for case-insensitive string comparison
**Next up (Day 4):**
Building on loops and dictionaries to process structured business data.
Save the notebook to GitHub
Publishing to GitHub makes your notebook accessible via a shareable link. It also lets you attach an Open in Colab badge so anyone can run your code with one click.
- In the Colab menu bar, click File.
- Click Save a copy in GitHub.
- If prompted, authorize Colab to access your GitHub account.
- In the Repository dropdown, select your python-portfolio repository.
- Leave the Branch as main.
- In the Commit message field, type Add Day 3 Automatic Desktop Organizer notebook.
- Click OK to save.
What does saving to GitHub do?
Colab pushes the .ipynb file directly into your python-portfolio repository. This is equivalent to committing and pushing from a terminal, but done entirely through the Colab interface.
- After the save completes, Colab opens your GitHub repository in a new tab. Confirm you see Day_3_Automatic_Desktop_Organizer.ipynb in the file list.
Don't see the repository in the dropdown?
Make sure your python-portfolio repository is public. Private repositories require granting Colab additional permissions during the authorization step.
If you authorized Colab previously but the repo still does not appear, revoke the Colab GitHub integration from your GitHub Settings > Applications page, then try File > Save a copy in GitHub again to re-authorize.
help me connect Colab to my GitHub repository
Add an Open in Colab badge to your README
The badge gives visitors a one-click button to open your notebook in Colab. You will edit the README.md file directly on GitHub.
- In your python-portfolio repository on GitHub, click the README.md file.
- Click the pencil icon (Edit this file) in the top right of the file view.
- Scroll to the bottom of the existing README content.
- Add the following markdown at the bottom:
## Day 3: Automatic Desktop Organizer
[](https://colab.research.google.com/github/[[GITHUB_USERNAME="your-github-username"]]/python-portfolio/blob/main/Day_3_Automatic_Desktop_Organizer.ipynb)
What does this badge do?
The badge image is hosted by Google at colab.research.google.com/assets/colab-badge.svg. The link wraps that image and points to your notebook file inside the repository.
When someone clicks it, Colab opens your notebook directly from GitHub. They can run all three cells without cloning or downloading anything.
- Click Commit changes in the top right.
- In the commit dialog, leave the default commit message and click Commit changes again to confirm.
- Navigate back to the main page of your python-portfolio repository.
- Scroll down to the README. You should see an Open In Colab badge under the Day 3 heading.
- Click the badge to test it. A new Colab tab should open with your Day_3_Automatic_Desktop_Organizer.ipynb notebook loaded and ready to run.
Badge shows a broken image or 404?
Double-check that the URL inside the parentheses matches your exact GitHub username and that the filename is Day_3_Automatic_Desktop_Organizer.ipynb with underscores, not spaces.
The branch must be main (not master). If your repository uses a different default branch name, update the URL to match.
help me fix my Open in Colab badge link
Your notebook is documented, published, and shareable. Anyone with the link can click the badge and run your organizer without installing anything. Next up, you will extend the organizer with a Secret Mission challenge.
Secret mission
File Organization Summary Report
Your organizer works great for known file types. But what happens when someone drops a .sql database backup or a .yaml config file on the desktop? In this challenge, you will enhance the organizer to handle unknown extensions and generate a professional summary report with per-category counts, a text bar chart, and recommendations.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely on free services. There are no ongoing costs, no paid APIs, and no cloud resources to worry about.
Decide whether to keep your resources as they are, disconnect your Colab session, or delete everything entirely.
What about the /content/messy_desktop folder?
The /content/messy_desktop folder exists only while your Colab session is active. It disappears automatically when the session ends. No persistent storage is used.
Resources you used:
- Day_3_Automatic_Desktop_Organizer.ipynb notebook in Google Drive (free, no ongoing cost).
- Updated python-portfolio repository on GitHub (free, no ongoing cost).
Keep everything running
No action needed. Choose this if you are continuing the Python series or plan to share your notebook soon.
- Your notebook stays in Google Drive and is accessible anytime.
- Your python-portfolio repository stays on GitHub with the Open in Colab badge ready to share.
- Neither service charges for storage at this scale.
Pause - I'll come back to this later
Disconnect the Colab runtime to free up session resources. Your notebook file stays saved in Google Drive.
- In your Colab notebook, click Runtime in the top menu bar.
- Click Disconnect and delete runtime.
- This frees up the session memory and deletes the temporary /content/messy_desktop folder. Your notebook code remains saved in Drive.
- When you return, just click the play buttons to regenerate the files and re-run the organizer.
Delete - I don't want to use this again
Remove all project resources from Google Drive and GitHub.
- Delete the notebook from Google Drive: open Google Drive, find Day_3_Automatic_Desktop_Organizer.ipynb, right-click it, and select Move to trash.
- Remove the Day 3 file from GitHub: navigate to your python-portfolio repository, click on Day_3_Automatic_Desktop_Organizer.ipynb, click the three-dot menu, and select Delete file. Commit the change.
- Update your README.md to remove the Day 3 heading and Open in Colab badge if desired.
- The Colab runtime (and the /content/messy_desktop folder) will disappear automatically when the session ends. No manual cleanup needed there.
Nice Work!
Nice Work!
Nice work! You just built an Automatic Desktop Organizer that creates 25 realistic business files and sorts them into 5 clean category folders using Python.
You've learned how to:
- Use dictionaries to map 8 file extensions to 5 folder categories, replacing long chains of if/elif statements with a single data structure.
- Automate file operations with the os and shutil modules to create folders, extract extensions, and move files programmatically.
- Create a sandbox-ready notebook with hidden code cells and an Open in Colab badge, published to GitHub for sharing on social media.
- Secret Mission: Added a summary report with per-category text bar charts, timestamps, and unknown file type detection routed to an "Other" folder.
Ready to quiz yourself?