Mini Project: File Organizer
Exit

Mini Project: File Organizer

Build a CLI tool that sorts files into folders by extension

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

What you are building

A file organizer that takes a directory path and sorts its files into subfolders by extension. Running it on a messy Downloads folder creates folders like pdf/, jpg/, txt/, and moves each file to the matching folder.

This project combines everything from this lesson:

  • pathlib — scan directories and build paths
  • argparse — accept the target directory as a CLI argument
  • os — create subdirectories

The algorithm

  1. Accept a directory path from the command line
  2. List all files in that directory (skip subdirectories)
  3. For each file, get its extension (e.g., .pdfpdf)
  4. Create a subdirectory named after the extension (if it doesn't exist)
  5. Print a message for each file showing where it would move

For safety, your organizer will print the planned moves instead of actually moving files. This is a common pattern in CLI tools — a "dry run" mode that shows what would happen.

Your task

Build the organize_files function and the CLI interface. The function takes a directory path string, scans it, and prints the move plan. The argparse setup accepts the directory as a positional argument.

You will use parse_args(["test_folder"]) to simulate running the command with a test directory — this lets you test the argument parsing in the code editor.

Instructions

Build the file organizer.

  1. Define organize_files(directory). Create a variable named path and assign it Path(directory).
  2. Inside the function, create a variable named files and assign it a list comprehension: [f for f in path.iterdir() if f.is_file()].
  3. Inside the function, create a variable named extensions and assign it Counter(f.suffix.lower() for f in files if f.suffix).
  4. Inside the function, loop through files with loop variable file. Inside the loop, if file.suffix is truthy, create a variable named ext_folder and assign it file.suffix[1:].lower(). Call print() with f" {file.name} -> {ext_folder}/{file.name}".
  5. Call print() with f"\nSummary: {len(files)} files". Loop through extensions.most_common() with loop variable ext, count. Inside the loop, call print() with f" {ext}: {count} files".
  6. After the function definition, import argparse. Create a variable named parser and assign it argparse.ArgumentParser(description="Organize files by extension"). Call parser.add_argument("directory", help="Directory to organize").
  7. Create a variable named args and assign it parser.parse_args(["test_folder"]).
  8. Call print() with f"Organizing: {args.directory}". Call organize_files(args.directory).