Python File Organizer Script

In the last lesson, Python Password Generator, we built a tool that creates strong random passwords. Now we will build a file organizer script that automatically sorts files into folders.

In this tutorial, we will build a Python File Organizer Script from scratch using VS Code. This is a practical automation project that teaches file handling, Python modules such as os and shutil, dictionaries, loops, and functions. By the end, we will have a script that scans a folder and automatically sorts files into subfolders based on their file type.

What Is a File Organizer Script?

A File Organizer Script is a program that automatically moves files into folders based on their type. For example, images go into an Images folder, documents go into a Documents folder, and so on.

Think of it like a robot assistant that cleans up your messy Downloads folder. It looks at each file, checks its extension, and moves it to the right place.

File organizers are useful for keeping our computer organized. They save time and reduce clutter. And they are a great way to practice working with files and folders in Python.

Features of Our Python File Organizer Script

Our File Organizer will have these features:

  • Scan a folder for files
  • Sort files by extension into subfolders
  • Handle unknown extensions (go into an Others folder)
  • Avoid overwriting files with the same name
  • Print a summary of what was moved

Project Folder Structure

We will create a folder for our project. Inside it, we will have one Python file and a test folder for our files.

file_organizer/
organizer.py
test_folder/
(our test files go here)

There is no data file for this project. The script works directly with files on the computer.

Let us set up the project in VS Code.

Setting Up the Project in VS Code

Step 1: Open VS Code

If we do not have VS Code installed, we can download it from code.visualstudio.com. It is free.

Once installed, open VS Code.

Step 2: Create a New Folder

  • Click on File in the top menu.
  • Click Open Folder.
  • Navigate to where we want to keep our project (like Desktop or Documents).
  • Click New Folder.
  • Name it file_organizer.
  • Click Select Folder.

Now VS Code is open with our new empty folder.

Step 3: Create the Python File and Test Folder

  • In the left sidebar, we see our folder name file_organizer.
  • Right-click on the folder name.
  • Click New File.
  • Name it organizer.py.
  • Press Enter.

Now create a test folder. Right-click on the file_organizer folder again, click New Folder, and name it test_folder.

Now we have an empty organizer.py file and an empty test_folder ready.

Step 4: Open the Integrated Terminal

  • Click on Terminal in the top menu.
  • Click New Terminal.

A terminal panel opens at the bottom. It is already inside our file_organizer folder. So we do not need to cd anywhere.

Now we are ready to write code.

How to Create the File Organizer Script in Python (Step by Step)

We will write the code in small steps. Before each step, we will explain what we are doing and why. We will mention which file we are editing (always organizer.py in this project).

Step 1: Import Required Modules

We need two modules. os for working with files and folders, and shutil for moving files.

organizer.py
import os
import shutil

Step 2: Define Categories and Extensions

We will create a dictionary that maps category names to lists of file extensions. This tells the script which files go where.

organizer.py
CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg"],
"Documents": [".pdf", ".doc", ".docx", ".txt", ".xls", ".xlsx", ".ppt", ".pptx"],
"Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"],
"Music": [".mp3", ".wav", ".flac", ".aac"],
"Archives": [".zip", ".rar", ".7z", ".tar", ".gz"],
"Code": [".py", ".js", ".html", ".css", ".java", ".c", ".cpp"],
"Others": []
}

Anything not matched will go into Others.

Step 3: Create a Function to Find the Category

We loop through the categories and check if the file extension matches. If not, we return Others.

organizer.py
def get_category(extension):
for category, extensions in CATEGORIES.items():
if extension.lower() in extensions:
return category
return "Others"

Step 4: Create a Function to Avoid Overwriting Files

If a file with the same name already exists in the destination folder, we add a number to the name. For example, photo.jpg becomes photo_1.jpg.

organizer.py
def avoid_overwrite(destination):
if not os.path.exists(destination):
return destination
base, extension = os.path.splitext(destination)
counter = 1
new_destination = f"{base}_{counter}{extension}"
while os.path.exists(new_destination):
counter += 1
new_destination = f"{base}_{counter}{extension}"
return new_destination

Step 5: Create the Main Organizing Function

This function scans the folder, finds each file, determines its category, creates the category folder if needed, and moves the file.

organizer.py
def organize_folder(folder_path):
if not os.path.exists(folder_path):
print(f"Folder not found: {folder_path}")
return
moved_count = 0
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isdir(file_path):
continue
_, extension = os.path.splitext(filename)
category = get_category(extension)
category_folder = os.path.join(folder_path, category)
if not os.path.exists(category_folder):
os.makedirs(category_folder)
destination = os.path.join(category_folder, filename)
destination = avoid_overwrite(destination)
shutil.move(file_path, destination)
print(f"Moved: {filename} -> {category}/")
moved_count += 1
print(f"\nTotal files moved: {moved_count}")

Step 6: Create the Main Function

We ask the user for the folder path to organize. If they do not enter anything, we use the default test_folder.

organizer.py
def main():
folder = input("Enter folder path to organize: ").strip()
if not folder:
folder = "test_folder"
print(f"\nOrganizing: {folder}\n")
organize_folder(folder)

Step 7: Run the File Organizer Program

Finally, let us add the program entry point.

organizer.py
if __name__ == "__main__":
main()

Complete Python File Organizer Script Code

Now our complete organizer.py file looks like this.

import os
import shutil
CATEGORIES = {
"Images": [".jpg", ".jpeg", ".png", ".gif", ".bmp", ".svg"],
"Documents": [".pdf", ".doc", ".docx", ".txt", ".xls", ".xlsx", ".ppt", ".pptx"],
"Videos": [".mp4", ".avi", ".mkv", ".mov", ".wmv"],
"Music": [".mp3", ".wav", ".flac", ".aac"],
"Archives": [".zip", ".rar", ".7z", ".tar", ".gz"],
"Code": [".py", ".js", ".html", ".css", ".java", ".c", ".cpp"],
"Others": []
}
def get_category(extension):
for category, extensions in CATEGORIES.items():
if extension.lower() in extensions:
return category
return "Others"
def avoid_overwrite(destination):
if not os.path.exists(destination):
return destination
base, extension = os.path.splitext(destination)
counter = 1
new_destination = f"{base}_{counter}{extension}"
while os.path.exists(new_destination):
counter += 1
new_destination = f"{base}_{counter}{extension}"
return new_destination
def organize_folder(folder_path):
if not os.path.exists(folder_path):
print(f"Folder not found: {folder_path}")
return
moved_count = 0
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isdir(file_path):
continue
_, extension = os.path.splitext(filename)
category = get_category(extension)
category_folder = os.path.join(folder_path, category)
if not os.path.exists(category_folder):
os.makedirs(category_folder)
destination = os.path.join(category_folder, filename)
destination = avoid_overwrite(destination)
shutil.move(file_path, destination)
print(f"Moved: {filename} -> {category}/")
moved_count += 1
print(f"\nTotal files moved: {moved_count}")
def main():
folder = input("Enter folder path to organize: ").strip()
if not folder:
folder = "test_folder"
print(f"\nOrganizing: {folder}\n")
organize_folder(folder)
if __name__ == "__main__":
main()

How to Test the File Organizer in VS Code

First, we need some test files. We can create them manually or use the terminal.

Open the VS Code terminal and run these commands to create a few test files inside test_folder.

Terminal window
cd test_folder
touch photo1.jpg photo2.png report.pdf notes.txt song.mp3 video.mp4 archive.zip script.py
cd ..

Now run the organizer.

Terminal window
python organizer.py

Enter test_folder when asked.

Example Output

Enter folder path to organize: test_folder
Organizing: test_folder
Moved: photo1.jpg -> Images/
Moved: photo2.png -> Images/
Moved: report.pdf -> Documents/
Moved: notes.txt -> Documents/
Moved: song.mp3 -> Music/
Moved: video.mp4 -> Videos/
Moved: archive.zip -> Archives/
Moved: script.py -> Code/
Total files moved: 8

Now if we look inside test_folder, we will see subfolders Images, Documents, Music, Videos, Archives, and Code. Each one contains the right files.

That is our File Organizer Script. It is simple but powerful. And we built it entirely in VS Code.

Exercises for Practice

Try these exercises to improve the File Organizer Script.

  1. Add a dry-run mode that shows what would be moved without actually moving files.
  2. Add an undo feature that moves files back to their original location.
  3. Add sorting by date so files older than a certain date go into an Old folder.
  4. Add a config file that lets the user define their own categories and extensions.
  5. Add a log file that records every move with a timestamp.
  6. Add a feature to sort files by size (small, medium, large).
  7. Add a menu that lets the user choose which folder to organize without typing the path.

That completes all six projects in our Python project series. We built a To-Do app, a Calculator, an Expense Tracker, a Student Management System, a Password Generator, and a File Organizer Script. Each project used different skills and modules. Together, they cover the core of Python programming for beginners.