Build a File Organizer with Python
Write a Python script that automatically sorts files into folders by type.
Introduction
30 Second Summary
Everyone's been there. Your Downloads folder is a mess of PDFs, images, spreadsheets, and random files piled on top of each other.
In this project, you will write a Python script that automatically sorts files into neat folders based on their type. You'll learn Python's core building blocks while creating a tool you'll actually keep using.
What You'll Build
A command-line Python script that scans a folder and moves each file into a categorized subfolder based on its extension.
By the end of this project, you'll have:
- A working Python script that categorizes and moves files by extension.
- Hands-on experience with Python's core building blocks: variables, functions, loops, conditionals, and dictionaries.
- A reusable automation tool you can run anytime your folders get messy.
- Secret Mission: Add a logging feature that saves a history of every file move to a text file.
Are there any prerequisites?
You'll need Python and a code editor (like VS Code) installed on your computer. No prior coding experience is required. Step 1 walks you through verifying your setup.
Before We Start
Before We Start...
Verify Your Setup
Before writing any code, you need to confirm that Python is ready to run on your machine.
In this step, you'll verify your Python installation, create a dedicated project folder, and run your first test script to make sure everything connects properly.
In this step, get ready to:
- Confirm Python is installed and working.
- Create a project folder and open it in VS Code.
- Create and run your first Python file.
Confirm Python is installed
Python is the language your file organizer script will run on. Let's make sure it's ready to go.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Terminal (macOS) or PowerShell (Windows) and press Enter to open it.
- Check your Python version by running the command for your operating system:
macOS
python3 --version
Windows
python --version
You should see a version number printed, like Python 3.x.x.
✔️ I see a version number
Python is ready to go. Move on to the next substep.
ⓧ Command not found
This means Python isn't in your system's PATH. Visit the official Python downloads page at python.org/downloads and install the latest version.
On Windows, make sure to check the box that says Add python.exe to PATH during installation. After installing, close and reopen your terminal, then try the command again.
Create your project folder
Every project needs its own folder to keep files organized. You'll create one on your Desktop so it's easy to find.
- Move to your Desktop by running this command:
cd ~/Desktop
- Create your project folder and move into it by running these commands:
mkdir file-organizer
cd file-organizer
- Confirm the folder exists by running:
ls
The output will be empty since the folder is brand new. That's expected.
Seeing an error with mkdir?
If you see a message saying the folder already exists, that's fine. Just run cd file-organizer to move into the existing folder.
help me fix a mkdir error in my terminal
Now open VS Code with your project folder.
- Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Visual Studio Code and press Enter to open it.
- In VS Code, click File in the top menu bar.
- Click Open Folder.
- Navigate to your Desktop, select the file-organizer folder, and click Open.
Why open a folder instead of just a file?
Opening the entire folder gives VS Code context about your project. You'll see all your project files in the Explorer sidebar on the left, making it easy to create and switch between files as your project grows.
Create and run your first Python file
With your folder open in VS Code, you'll create the script file that will eventually become your file organizer. For now, a simple test confirms everything is connected.
- In VS Code's Explorer sidebar on the left, hover over the FILE-ORGANIZER heading.
- Click the New File icon (it looks like a page with a plus sign).
- Type organizer.py and press Enter.
- Add this code to your new organizer.py file:
print("Hello, File Organizer!")
What does this code do?
print() is a built-in Python function that outputs text to your terminal. It's the simplest way to confirm your script runs correctly.
- Save the file with Cmd+S (macOS) or Ctrl+S (Windows).
- Open the built-in terminal in VS Code by pressing Ctrl+` (macOS and Windows). This opens a terminal already pointed at your file-organizer folder.
- Run your script with the command for your operating system:
macOS
python3 organizer.py
Windows
python organizer.py
You should see Hello, File Organizer! printed in your terminal.
✔️ I see Hello, File Organizer!
Your Python setup is working perfectly. You're ready to start building.
ⓧ I see an error
Check that you saved organizer.py before running the command. Also make sure your terminal is pointed at the file-organizer folder.
If you see No such file or directory, the terminal is in a different folder than where your file lives. Close the terminal with the trash icon and reopen it with Ctrl+` to reset it to your project folder.
help me run my Python script in VS Code
✔️ Awesome, I've got everything!
Great. Double check you've saved your file before moving on.
ⓧ I'd like to double check the full code
Here's what organizer.py should look like:
print("Hello, File Organizer!")
Your environment is ready. Next up, you'll create a test folder full of sample files to give your organizer something to work with.
Create a Test Folder with Sample Files
Your environment is ready and Python is confirmed working. Now you need some files to practice organizing.
In this step, you'll write a function that creates a test folder filled with sample files of different types. This gives you a safe playground to run your organizer on without touching any real files on your computer.
In this step, get ready to:
- Import Python's pathlib module for working with files and folders.
- Create a function that generates a test_files folder with 8 sample files.
- Run the script and confirm the files appear on disk.
Import pathlib and set up folder creation
Python's pathlib module gives you an object-oriented way to work with file paths. Instead of using plain text strings, you get Path objects with built-in methods for creating, reading, and navigating files and folders.
- In VS Code, select all existing code in organizer.py and delete it.
- Replace it with this code to start building your create_test_files function:
from pathlib import Path
def create_test_files(folder_path):
"""Create a test folder with sample files for practicing."""
folder = Path(folder_path)
folder.mkdir(exist_ok=True)
What does this code do?
- from pathlib import Path imports the Path class from Python's standard library.
- def create_test_files(folder_path): defines a reusable function that accepts a folder name as input.
- Path(folder_path) converts the plain text string into a Path object you can call methods on.
- folder.mkdir(exist_ok=True) creates the folder. The exist_ok=True part prevents a crash if the folder already exists.
- Save organizer.py.
- You won't see a change yet. The next chunk adds the file creation logic that this function needs.
Add sample file creation inside the function
Now you'll define which files to create and write a loop that generates them one by one.
- In organizer.py, find the folder.mkdir(exist_ok=True) line. Copy the following code directly below it, making sure it stays indented with 4 spaces (inside the function):
sample_files = [
"report.pdf",
"photo.jpg",
"song.mp3",
"notes.txt",
"spreadsheet.xlsx",
"video.mp4",
"presentation.pptx",
"script.py",
]
for filename in sample_files:
file_path = folder / filename
file_path.touch()
print(f"Created {len(sample_files)} sample files in '{folder_path}/'")
What does this code do?
- sample_files is a list holding 8 filenames with different extensions (PDF, image, audio, video, code).
- The for loop goes through each filename in the list, one at a time.
- folder / filename uses pathlib's / operator to build a full file path (like test_files/report.pdf).
- .touch() creates an empty file at that path. It works like tapping a blank sheet of paper into existence.
- The print() at the end confirms how many files were created.
- Save organizer.py.
- You won't see a change yet. The next substep adds the code that actually calls this function.
Run the script and verify your files
The function is ready, but nothing calls it yet. Python uses a special if __name__ == "__main__": block to define what runs when you execute the script directly.
- At the very bottom of organizer.py (outside the function, with no indentation), add this code:
if __name__ == "__main__":
test_folder = "test_files"
create_test_files(test_folder)
What does this code do?
- if __name__ == "__main__": means this code only runs when you execute the script directly (not when it's imported by another file).
- test_folder = "test_files" stores the folder name in a variable so it's easy to change later.
- create_test_files(test_folder) calls your function and kicks off the file creation.
- Save organizer.py.
- Run the script by executing this command in your terminal:
python organizer.py
- You should see this output in your terminal: Created 8 sample files in 'test_files/'.
- Confirm the files exist by running:
ls test_files
- You should see all 8 filenames listed: report.pdf, photo.jpg, song.mp3, notes.txt, spreadsheet.xlsx, video.mp4, presentation.pptx, and script.py.
Not seeing the expected output?
- Make sure you saved organizer.py before running the command.
- Check that the if __name__ block is at the bottom of the file with no indentation (it should start at column 1).
- Verify the function call uses the exact name create_test_files matching the function definition above.
- If you see an indentation error, make sure the sample_files list and for loop are indented with exactly 4 spaces inside the function.
Still stuck? Ask for help: Why isn't my Python script creating the test_files folder and sample files?
✔️ Awesome, I've got everything!
Great. Double check you've saved your file and move on to the next step.
ⓧ I'd like to double check the full code
Here's what your complete organizer.py should look like at this point:
from pathlib import Path
def create_test_files(folder_path):
"""Create a test folder with sample files for practicing."""
folder = Path(folder_path)
folder.mkdir(exist_ok=True)
sample_files = [
"report.pdf",
"photo.jpg",
"song.mp3",
"notes.txt",
"spreadsheet.xlsx",
"video.mp4",
"presentation.pptx",
"script.py",
]
for filename in sample_files:
file_path = folder / filename
file_path.touch()
print(f"Created {len(sample_files)} sample files in '{folder_path}/'")
if __name__ == "__main__":
test_folder = "test_files"
create_test_files(test_folder)
Your test playground is ready with 8 files of different types waiting to be organized. Next up, you'll build a dictionary that maps each file extension to a category like Images, Documents, or Music.
Define File Categories with a Dictionary
Your test files are ready. Now you need a way to tell the script which files belong in which folder.
Python dictionaries are perfect for this. They let you map a label (like "Images") to a collection of related values (like .jpg, .png, .gif). In this step, you'll define those categories and write a function that looks up any file extension.
In this step, get ready to:
- Create a dictionary mapping category names to file extensions.
- Write a function that returns the category for any given extension.
- Test the function to confirm it works.
Create the FILE_CATEGORIES dictionary
The organizer needs a lookup table that connects each category name to the file extensions that belong in it. A Python dictionary stores this as key-value pairs.
- Switch back to organizer.py in VS Code.
- Find the blank line between your from pathlib import Path import and the def create_test_files function.
- Add the following dictionary in that space:
# --- File category definitions ---
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp"],
"Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".xls", ".pptx", ".ppt", ".csv"],
"Music": [".mp3", ".wav", ".flac", ".aac", ".ogg"],
"Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"],
"Code": [".py", ".js", ".html", ".css", ".java", ".cpp", ".c"],
}
What does this code do?
A dictionary in Python uses curly braces {} to store pairs of keys and values.
- Each key (like "Images") is a category name that will become a subfolder.
- Each value is a list of file extensions that belong in that category.
- The variable name FILE_CATEGORIES is in all caps because it's a constant. The data never changes while the script runs.
- Save organizer.py.
Seeing a syntax error?
- Make sure every opening bracket [ and { has a matching closing bracket ] and }.
- Check that each extension is in quotes (".jpg") and separated by commas.
- Confirm the dictionary is placed after the import line and before def create_test_files, with a blank line above and below it.
Help me fix a syntax error in my FILE_CATEGORIES dictionary
Write the get_category function
The dictionary holds all the mappings, but you need a function that takes a file extension and searches the dictionary for a match. If nothing matches, it should return a fallback category.
- In organizer.py, add the following function directly below the FILE_CATEGORIES dictionary (and above def create_test_files):
def get_category(extension):
"""Return the category name for a given file extension."""
for category, extensions in FILE_CATEGORIES.items():
if extension in extensions:
return category
return "Other"
What does this code do?
- The function takes one argument: extension (like ".jpg").
- The for loop uses .items() to unpack each dictionary entry into two variables: category (the key) and extensions (the list of extensions).
- If the extension is found in the list, the function immediately returns the category name.
- If the loop finishes without finding a match, it falls through to return "Other". This catches any file type not in your dictionary.
- Save organizer.py.
You won't see a change yet. The next chunk tests this function and shows output in your terminal.
Indentation looking off?
- Python is strict about indentation. Every line inside the function must be indented by exactly 4 spaces.
- The for loop body needs 8 spaces (4 for the function, 4 for the loop).
- Make sure return "Other" is at the same level as the for keyword (4 spaces), not inside the loop.
Help me fix indentation in my get_category function
Test the function
Before building more features on top of this function, you should confirm it returns the right category for known extensions and falls back to "Other" for unknown ones.
- In organizer.py, scroll down to the if __name__ == "__main__": block at the bottom of the file.
- Find this line:
create_test_files(test_folder)
- Add these two lines directly below it:
print(get_category(".jpg")) # Should print: Images
print(get_category(".xyz")) # Should print: Other
What does this code do?
These two lines call your new function with a known extension (.jpg) and an unknown one (.xyz). If your dictionary and function are working correctly, the terminal will print Images and Other.
- Save organizer.py.
- Run the script in your terminal:
python organizer.py
- You should see three lines of output: the "Created 8 sample files" message from the previous step, then Images, then Other.
Not seeing Images and Other?
- Check that the two print(get_category(...)) lines are indented with 4 spaces (inside the if __name__ block, not at the top level).
- Make sure FILE_CATEGORIES and get_category are defined above the if __name__ block, not inside it.
- Confirm the extension strings include the dot: ".jpg" not "jpg".
Help me debug my get_category function output
✔️ Awesome, I've got everything!
Great. Double check you've saved your file.
ⓧ I'd like to double check the full code
from pathlib import Path
# --- File category definitions ---
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp"],
"Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".xls", ".pptx", ".ppt", ".csv"],
"Music": [".mp3", ".wav", ".flac", ".aac", ".ogg"],
"Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"],
"Code": [".py", ".js", ".html", ".css", ".java", ".cpp", ".c"],
}
def get_category(extension):
"""Return the category name for a given file extension."""
for category, extensions in FILE_CATEGORIES.items():
if extension in extensions:
return category
return "Other"
def create_test_files(folder_path):
"""Create a test folder with sample files for practicing."""
folder = Path(folder_path)
folder.mkdir(exist_ok=True)
sample_files = [
"report.pdf",
"photo.jpg",
"song.mp3",
"notes.txt",
"spreadsheet.xlsx",
"video.mp4",
"presentation.pptx",
"script.py",
]
for filename in sample_files:
file_path = folder / filename
file_path.touch()
print(f"Created {len(sample_files)} sample files in '{folder_path}/'")
if __name__ == "__main__":
test_folder = "test_files"
create_test_files(test_folder)
print(get_category(".jpg")) # Should print: Images
print(get_category(".xyz")) # Should print: Other
Your file categories are locked in and the lookup function is working. Next up, you'll use these pieces to actually move files into their matching folders.
Build the Organize Function
You have a dictionary that maps file types to categories and a function that looks up any extension. Now it's time to put these pieces together into the function that actually moves files.
The organize_folder function will scan every file in a folder, determine its category, create the right subfolder, and move the file into it.
In this step, get ready to:
- Import the shutil module for moving files.
- Write a function that loops through files and sorts them into category subfolders.
- Add terminal output showing each file move and a final summary.
Import shutil for moving files
Python's pathlib module is great for navigating the file system, but it doesn't have a built-in way to move files between folders. The shutil module fills that gap.
- In organizer.py, find the import line at the top of the file:
from pathlib import Path
- Add import shutil on the line directly below it, so the top of your file looks like this:
from pathlib import Path
import shutil
What is shutil?
shutil (short for "shell utilities") is a Python standard library module that handles high-level file operations like moving, copying, and deleting files. It's part of Python already, so you don't need to install anything.
Write the organize_folder function
This function will loop through every item in a folder, check if it's a file, look up its category, and move it into the right subfolder.
- In organizer.py, find the if __name__ == "__main__": block at the bottom of your file and delete that entire block (the if line plus everything indented under it).
- Add the following function at the bottom of your file, below the create_test_files function:
def organize_folder(folder_path):
"""Organize all files in a folder into category subfolders."""
folder = Path(folder_path)
moved_count = 0
for item in folder.iterdir():
if item.is_file():
extension = item.suffix.lower()
category = get_category(extension)
# Create the category subfolder
destination_folder = folder / category
destination_folder.mkdir(exist_ok=True)
# Move the file
destination = destination_folder / item.name
shutil.move(str(item), str(destination))
print(f" Moved {item.name} -> {category}/")
moved_count += 1
print(f"\nDone! Organized {moved_count} files.")
What does this code do?
This function has three responsibilities working together inside a loop:
- folder.iterdir() scans every item in the folder. item.is_file() skips subdirectories so you only process actual files.
- item.suffix.lower() grabs the file extension (like .pdf) in lowercase. Then get_category() looks it up in your dictionary, mkdir creates the subfolder, and shutil.move() moves the file.
- moved_count tracks how many files were moved. Each move prints a line, and the final print() at the end shows the total.
Why wrap paths in str()?
shutil.move() may not accept Path objects directly in older Python versions. Wrapping in str() ensures your script works across all Python 3 versions.
- Save organizer.py.
Seeing a red underline on shutil?
Make sure your import shutil line is at the very top of the file, directly below from pathlib import Path. If VS Code still shows an error, try saving the file and waiting a moment for the editor to re-check.
Help me fix an import error in my Python file.
Verify the function is ready to use
The function is defined but not called yet. You'll call it in the next step. For now, confirm your file has no errors.
- Run a quick syntax check by running this command in your terminal:
python organizer.py
You should see no output at all. That's expected. The old test prints are gone and the new function exists but isn't being called yet. No output and no errors means everything is wired up correctly.
Seeing a SyntaxError or IndentationError?
Check that every line inside the for loop is indented with spaces (not tabs). The if item.is_file(): line should be indented once from for, and everything inside the if block should be indented twice.
Also confirm you fully deleted the old if __name__ == "__main__": block. Leftover lines from that block can cause indentation conflicts.
Help me debug this Python error.
✔️ Awesome, I've got everything!
Great. Double check you've saved your file.
ⓧ I'd like to double check the full code
Here's the complete organizer.py file as it should look right now:
from pathlib import Path
import shutil
# --- File category definitions ---
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp"],
"Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".xls", ".pptx", ".ppt", ".csv"],
"Music": [".mp3", ".wav", ".flac", ".aac", ".ogg"],
"Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"],
"Code": [".py", ".js", ".html", ".css", ".java", ".cpp", ".c"],
}
def get_category(extension):
"""Return the category name for a given file extension."""
for category, extensions in FILE_CATEGORIES.items():
if extension in extensions:
return category
return "Other"
def create_test_files(folder_path):
"""Create a test folder with sample files for practicing."""
folder = Path(folder_path)
folder.mkdir(exist_ok=True)
sample_files = [
"report.pdf",
"photo.jpg",
"song.mp3",
"notes.txt",
"spreadsheet.xlsx",
"video.mp4",
"presentation.pptx",
"script.py",
]
for filename in sample_files:
file_path = folder / filename
file_path.touch()
print(f"Created {len(sample_files)} sample files in '{folder_path}/'")
def organize_folder(folder_path):
"""Organize all files in a folder into category subfolders."""
folder = Path(folder_path)
moved_count = 0
for item in folder.iterdir():
if item.is_file():
extension = item.suffix.lower()
category = get_category(extension)
# Create the category subfolder
destination_folder = folder / category
destination_folder.mkdir(exist_ok=True)
# Move the file
destination = destination_folder / item.name
shutil.move(str(item), str(destination))
print(f" Moved {item.name} -> {category}/")
moved_count += 1
print(f"\nDone! Organized {moved_count} files.")
Your organize function is ready to go. In the next step, you'll call it on your test folder and watch it sort all eight files into neat subfolders.
Run and Verify Your Organizer
Your organizer functions are built and ready. Now it's time to tie everything together with a main block and watch your script sort files in real time.
In this step, you'll add the entry point that actually runs your code, execute the script, and confirm the results by checking the folder structure.
In this step, get ready to:
- Add a main block that calls your functions.
- Run the script and watch the output.
- Verify that files landed in the correct subfolders.
Add a main block to your script
Python uses a special if __name__ == "__main__": block to define what happens when you run a script directly. Without it, your functions exist but nothing actually calls them.
- In organizer.py, scroll to the very bottom of the file (after the organize_folder function).
- Add the main block by pasting this code at the bottom:
if __name__ == "__main__":
test_folder = "test_files"
# Create test files to practice with
create_test_files(test_folder)
# Organize the files
print("\nOrganizing files...")
organize_folder(test_folder)
What does this code do?
This block only runs when you execute the script directly with python organizer.py. It won't run if another script imports your functions.
- test_folder = "test_files" stores the folder name in a variable so you can easily change it later.
- create_test_files(test_folder) ensures the sample files exist before organizing.
- organize_folder(test_folder) kicks off the actual sorting process.
- Save organizer.py.
Run the organizer script
Your script is complete. Time to run it and watch the organizer sort your files in real time.
- Run your organizer script by entering this command in your terminal:
python organizer.py
You should see output showing each file being moved to its category folder, followed by a summary of how many files were organized.
What should I see?
Your terminal prints a line for each file that gets moved. You'll see lines like Moved photo.jpg -> Images/ and Moved report.pdf -> Documents/. At the end, a summary reports the total number of files organized.
The exact order of files may vary. That's normal because Path.iterdir() doesn't guarantee a specific order.
Seeing an error instead of file moves?
- If you see NameError: name 'create_test_files' is not defined, make sure the main block is at the bottom of the file, after all function definitions.
- If you see IndentationError, check that everything inside the if __name__ block is indented with 4 spaces.
- If you see Done! Organized 0 files., the test files may have already been moved from a previous run. Delete the test_files folder and run the script again.
Help me debug my organizer script
Verify the organized folders
The terminal output tells you what happened. Now confirm it by looking at the actual folder structure.
- Open the test_files folder in Finder (macOS) or File Explorer (Windows).
- Confirm you see these subfolders: Code, Documents, Images, Music, and Videos.
- Open the Documents subfolder and confirm it contains report.pdf, notes.txt, spreadsheet.xlsx, and presentation.pptx.
- Open the Images subfolder and confirm it contains photo.jpg.
Why use a separate test folder?
The script organizes files inside test_files instead of the folder containing organizer.py. If you ran it on the same folder, the script would move itself into the Code subfolder. Using a separate test folder keeps things safe.
✔️ Awesome, I've got everything!
Great. Double check you've saved your file.
ⓧ I'd like to double check the full code
Here's the complete organizer.py file for comparison.
from pathlib import Path
import shutil
# --- File category definitions ---
FILE_CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg", ".webp"],
"Documents": [".pdf", ".docx", ".doc", ".txt", ".xlsx", ".xls", ".pptx", ".ppt", ".csv"],
"Music": [".mp3", ".wav", ".flac", ".aac", ".ogg"],
"Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"],
"Code": [".py", ".js", ".html", ".css", ".java", ".cpp", ".c"],
}
def get_category(extension):
"""Return the category name for a given file extension."""
for category, extensions in FILE_CATEGORIES.items():
if extension in extensions:
return category
return "Other"
def create_test_files(folder_path):
"""Create a test folder with sample files for practicing."""
folder = Path(folder_path)
folder.mkdir(exist_ok=True)
sample_files = [
"report.pdf",
"photo.jpg",
"song.mp3",
"notes.txt",
"spreadsheet.xlsx",
"video.mp4",
"presentation.pptx",
"script.py",
]
for filename in sample_files:
file_path = folder / filename
file_path.touch()
print(f"Created {len(sample_files)} sample files in '{folder_path}/'")
def organize_folder(folder_path):
"""Organize all files in a folder into category subfolders."""
folder = Path(folder_path)
moved_count = 0
for item in folder.iterdir():
if item.is_file():
extension = item.suffix.lower()
category = get_category(extension)
# Create the category subfolder
destination_folder = folder / category
destination_folder.mkdir(exist_ok=True)
# Move the file
destination = destination_folder / item.name
shutil.move(str(item), str(destination))
print(f" Moved {item.name} -> {category}/")
moved_count += 1
print(f"\nDone! Organized {moved_count} files.")
if __name__ == "__main__":
test_folder = "test_files"
# Create test files to practice with
create_test_files(test_folder)
# Organize the files
print("\nOrganizing files...")
organize_folder(test_folder)
Secret mission
Add Move Logging
Your organizer works, but what if you accidentally sort files into the wrong category? Right now there's no way to know what happened. Add a logging feature that records every move to a text file, so you always have a history of what went where.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely locally, so there are no ongoing costs. Decide whether to keep your project files, or delete them entirely.
Resources you used:
- The file-organizer project folder on your Desktop (contains organizer.py and the test_files folder with organized subfolders).
Keep everything running
No action needed. Choose this if you plan to keep experimenting with your file organizer or want to adapt it for other folders on your computer.
- Your file-organizer folder stays on your Desktop, ready to use anytime.
- You can run python organizer.py again whenever you want to organize new test files.
Pause - I'll come back to this later
Since this is a local project with no running processes, there is nothing to pause. Your files stay on disk until you delete them.
- Close the VS Code window if you want to free up memory.
- Close your terminal window.
- Your project folder remains on your Desktop whenever you want to return.
Delete - I don't want to use this again
Remove all project files from your computer. This deletes your script and all test files permanently.
- Close VS Code and any terminal windows open in the project folder.
- Open a new terminal window.
- Navigate to your Desktop and delete the project folder by running these commands:
macOS
cd ~/Desktop
rm -rf file-organizer
Windows
cd ~\Desktop
Remove-Item -Recurse -Force file-organizer
- Confirm the folder is gone by running:
ls
You should no longer see file-organizer in the output.
Nice Work!
Nice Work!
You just wrote your first real Python program. You now have a working automation script that declutters messy folders in seconds.
You've learned how to:
- Built a complete automation script using pathlib and shutil that scans a folder and sorts files into categorized subfolders.
- Used a dictionary to map file extensions to categories, and wrote reusable functions to keep your code organized.
- Combined for loops and conditionals to process each file and decide where it belongs.
- Added file I/O logging with timestamps to move_history.txt, creating a full record of every move.
Ready to quiz yourself?