w3resource

Python File Organizer Project - Solutions and Explanations


File Organizer:

Create a program that organizes files in a directory based on their types.

Input values:
User specifies the directory path to be organized.

Output value:
Files in the specified directory "temp" into subdirectories based on their types (e.g., images, pdfs, videos).

Example:

Input values:
Input directory path: /path/to/temp
Output value:
Files in /path/to/temp organized:
- images/
- image1.jpg
- image2.png
- documents/
- document1.pdf
- videos/
- video1.mp4

Here are two different solutions for a "File Organizer" program in Python. This program will organize files in a specified directory into subdirectories based on their file types (e.g., images, documents.

Solution 1: Basic Approach Using 'os' and 'shutil' Modules

Code:

# Solution 1: Basic Approach Using `os` and `shutil` Modules

import os  # Provides functions for interacting with the operating system
import shutil  # Provides functions for file operations like copying and moving

# Define file type categories and their corresponding extensions
FILE_TYPES = {
    'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
    'documents': ['.pdf', '.doc', '.docx', '.txt'],
    'videos': ['.mp4', '.mov', '.avi', '.mkv'],
    'audio': ['.mp3', '.wav', '.flac'],
    'archives': ['.zip', '.rar', '.7z', '.tar', '.gz']
}

def organize_files(directory_path):
    """Organize files in the given directory based on their types."""
    # Iterate over each file in the specified directory
    for filename in os.listdir(directory_path):
        # Get the file extension
        file_extension = os.path.splitext(filename)[1].lower()

        # Determine the category for the file based on its extension
        category = None
        for key, extensions in FILE_TYPES.items():
            if file_extension in extensions:
                category = key
                break

        # If the file matches a known category, move it to the corresponding subdirectory
        if category:
            category_path = os.path.join(directory_path, category)
            # Create the subdirectory if it doesn't exist
            os.makedirs(category_path, exist_ok=True)

            # Move the file to the subdirectory
            source = os.path.join(directory_path, filename)
            destination = os.path.join(category_path, filename)
            shutil.move(source, destination)
            print(f"Moved '{filename}' to '{category}/'")
        else:
            print(f"File '{filename}' does not match any known category.")

# Get the directory path from the user
directory_path = input("Enter the directory path to organize: ")

# Organize the files in the specified directory
organize_files(directory_path)

Output:

Enter the directory path to organize: i:/temp
Moved '23121500486326SBIN_ChallanReceipt-advance-tax-rg-24-25.pdf' to 'documents/'
Moved 'copy (online-video-cutter.com).mp4' to 'videos/'
Moved 'copy1 (online-video-cutter.com).mp4' to 'videos/'
File 'ErrorReport.csv' does not match any known category.
Moved 'Happy-Birthday-with-Voicemod-Text-to-Song.mp3' to 'audio/'
Moved 'PascalTriangleAnimated2.gif' to 'images/'
File 'PortfolioImportTemplate.xlsx' does not match any known category.
Moved 'python-tutorial-3.9.pdf' to 'documents/'
Moved 'WhatsApp Image 2024-02-03 at 7.51.06 PM.jpeg' to 'images/'

Explanation:

  • Uses the 'os' and 'shutil' modules to interact with the file system and move files.
  • Defines a dictionary 'FILE_TYPES' to map file categories to their respective extensions.
  • The 'organize_files()' function iterates over the files in the specified directory, determines the file type based on its extension, and moves it to the corresponding subdirectory.
  • Creates the subdirectory if it doesn't already exist using 'os.makedirs()'.
  • This solution is straightforward and works well for simple use cases but lacks structure for extensibility.

Solution 2: Using a Class-Based Approach for Organization and Extensibility

Code:

# Solution 2: Using a Class-Based Approach for Organization and Extensibility

import os  # Provides functions for interacting with the operating system
import shutil  # Provides functions for file operations like copying and moving

class FileOrganizer:
    """Class to handle file organization based on file types."""

    # Define file type categories and their corresponding extensions
    FILE_TYPES = {
        'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
        'documents': ['.pdf', '.doc', '.docx', '.txt'],
        'videos': ['.mp4', '.mov', '.avi', '.mkv'],
        'audio': ['.mp3', '.wav', '.flac'],
        'archives': ['.zip', '.rar', '.7z', '.tar', '.gz']
    }

    def __init__(self, directory_path):
        """Initialize the organizer with the specified directory path."""
        self.directory_path = directory_path

    def organize_files(self):
        """Organize files in the given directory based on their types."""
        # Iterate over each file in the specified directory
        for filename in os.listdir(self.directory_path):
            # Get the file extension
            file_extension = os.path.splitext(filename)[1].lower()

            # Determine the category for the file based on its extension
            category = self.get_category(file_extension)

            # If the file matches a known category, move it to the corresponding subdirectory
            if category:
                self.move_file(filename, category)
            else:
                print(f"File '{filename}' does not match any known category.")

    def get_category(self, file_extension):
        """Get the category for a file based on its extension."""
        for key, extensions in self.FILE_TYPES.items():
            if file_extension in extensions:
                return key
        return None

    def move_file(self, filename, category):
        """Move a file to the specified category directory."""
        category_path = os.path.join(self.directory_path, category)
        # Create the subdirectory if it doesn't exist
        os.makedirs(category_path, exist_ok=True)

        # Move the file to the subdirectory
        source = os.path.join(self.directory_path, filename)
        destination = os.path.join(category_path, filename)
        shutil.move(source, destination)
        print(f"Moved '{filename}' to '{category}/'")

# Get the directory path from the user
directory_path = input("Enter the directory path to organize: ")

# Create an instance of the FileOrganizer class
organizer = FileOrganizer(directory_path)

# Organize the files in the specified directory
organizer.organize_files()

Output:

Enter the directory path to organize: i:\temp
Moved '23121500486326SBIN_ChallanReceipt-advance-tax-rg-24-25.pdf' to 'documents/'
Moved 'copy (online-video-cutter.com).mp4' to 'videos/'
Moved 'copy1 (online-video-cutter.com).mp4' to 'videos/'
File 'ErrorReport.csv' does not match any known category.
Moved 'Happy-Birthday-with-Voicemod-Text-to-Song.mp3' to 'audio/'
Moved 'PascalTriangleAnimated2.gif' to 'images/'
File 'PortfolioImportTemplate.xlsx' does not match any known category.
Moved 'python-tutorial-3.9.pdf' to 'documents/'
Moved 'WhatsApp Image 2024-02-03 at 7.51.06 PM.jpeg' to 'images/'

Explanation:

  • Encapsulates the file organization logic within a 'FileOrganizer' class, making the code more modular and easier to maintain.
  • The '__init__()' method initializes the class with the directory path provided by the user.
  • The 'organize_files()' method handles the main logic of organizing files into subdirectories based on their types.
  • The 'get_category()' method determines the category of a file based on its extension.
  • The 'move_file()' method moves files to their respective subdirectories, creating the subdirectory if it doesn't exist.
  • This approach follows Object-Oriented Programming (OOP) principles, making it easier to extend and add new features (like handling additional file types).

Note:
Both solutions effectively organize files in a specified directory based on their types, with Solution 1 providing a basic function-based approach and Solution 2 offering a more organized, class-based design for better modularity and extensibility.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/projects/python/python-file-organizer-project.php