Skip to content

Automated File Mover

Abstract

Automated File Mover is a Python script that helps organize files by automatically moving them from a source directory to a destination directory based on their file extensions. The script targets specific file types (text, PDF, and image files) and provides feedback on each file moved. This project demonstrates file system operations, directory manipulation, and automated organization tasks. It’s an excellent tool for maintaining clean directories and automating repetitive file management tasks.

Prerequisites

  • Python 3.6 or above
  • A code editor or IDE
  • Read/write permissions for target directories

Before you Start

Before starting this project, you must have Python installed on your computer. If you don’t have Python installed, you can download it from here. You must have a code editor or IDE installed on your computer. If you don’t have any code editor or IDE installed, you can download Visual Studio Code from here.

Note: This project uses only built-in Python modules (osos and shutilshutil), so no additional installations are required.

Directory Setup

Before running the script, create the following directory structure:

project-folder/
├── automatedfilemover.py
├── source/          (create this folder and add test files)
└── destination/     (create this folder - files will be moved here)
project-folder/
├── automatedfilemover.py
├── source/          (create this folder and add test files)
└── destination/     (create this folder - files will be moved here)

Getting Started

Create a Project

  1. Create a folder named automated-file-moverautomated-file-mover.
  2. Open the folder in your favorite code editor or IDE.
  3. Create a file named automatedfilemover.pyautomatedfilemover.py.
  4. Create two subfolders: sourcesource and destinationdestination.
  5. Add some test files to the sourcesource folder (e.g., test.txt, image.png, document.pdf).
  6. Copy the given code and paste it in your automatedfilemover.pyautomatedfilemover.py file.

Write the Code

  1. Copy and paste the following code in your automatedfilemover.pyautomatedfilemover.py file.
⚙️ Automated File Mover
Automated File Mover
# Automated File Mover
 
import os
import shutil
 
# Set the source and destination directories
source = os.getcwd() + "/source/"
destination = os.getcwd() + "/destination/"
 
# Get the list of files in the source directory
files = os.listdir(source)
 
# Select File Types to Move
file_types = ["txt", "pdf", "png", "jpg", "jpeg"]
 
# Move the files to the destination directory
for file in files:
    for file_type in file_types:
        if file.endswith(file_type):
            shutil.move(source + file, destination + file)
            print("Moved " + file + " to " + destination + file)
            
# End of File
print("Move Complete") 
Automated File Mover
# Automated File Mover
 
import os
import shutil
 
# Set the source and destination directories
source = os.getcwd() + "/source/"
destination = os.getcwd() + "/destination/"
 
# Get the list of files in the source directory
files = os.listdir(source)
 
# Select File Types to Move
file_types = ["txt", "pdf", "png", "jpg", "jpeg"]
 
# Move the files to the destination directory
for file in files:
    for file_type in file_types:
        if file.endswith(file_type):
            shutil.move(source + file, destination + file)
            print("Moved " + file + " to " + destination + file)
            
# End of File
print("Move Complete") 
  1. Save the file.
  2. Open the terminal in your code editor or IDE and navigate to the folder automated-file-moverautomated-file-mover.
command
C:\Users\Your Name\automated-file-mover> python automatedfilemover.py
Moved document.txt to C:\Users\Your Name\automated-file-mover\destination\document.txt
Moved report.pdf to C:\Users\Your Name\automated-file-mover\destination\report.pdf
Moved photo.png to C:\Users\Your Name\automated-file-mover\destination\photo.png
Moved image.jpg to C:\Users\Your Name\automated-file-mover\destination\image.jpg
Move Complete
 
# All files with supported extensions are moved from source/ to destination/
command
C:\Users\Your Name\automated-file-mover> python automatedfilemover.py
Moved document.txt to C:\Users\Your Name\automated-file-mover\destination\document.txt
Moved report.pdf to C:\Users\Your Name\automated-file-mover\destination\report.pdf
Moved photo.png to C:\Users\Your Name\automated-file-mover\destination\photo.png
Moved image.jpg to C:\Users\Your Name\automated-file-mover\destination\image.jpg
Move Complete
 
# All files with supported extensions are moved from source/ to destination/

Explanation

Code Breakdown

  1. Import required modules for file operations.
automatedfilemover.py
import os
import shutil
automatedfilemover.py
import os
import shutil
  1. Set up source and destination directory paths.
automatedfilemover.py
source = os.getcwd() + "/source/"
destination = os.getcwd() + "/destination/"
automatedfilemover.py
source = os.getcwd() + "/source/"
destination = os.getcwd() + "/destination/"
  1. Get list of files in the source directory.
automatedfilemover.py
files = os.listdir(source)
automatedfilemover.py
files = os.listdir(source)
  1. Define target file types for organization.
automatedfilemover.py
file_types = ["txt", "pdf", "png", "jpg", "jpeg"]
automatedfilemover.py
file_types = ["txt", "pdf", "png", "jpg", "jpeg"]
  1. Move files based on their extensions.
automatedfilemover.py
for file in files:
    for file_type in file_types:
        if file.endswith(file_type):
            shutil.move(source + file, destination + file)
            print("Moved " + file + " to " + destination + file)
automatedfilemover.py
for file in files:
    for file_type in file_types:
        if file.endswith(file_type):
            shutil.move(source + file, destination + file)
            print("Moved " + file + " to " + destination + file)

Features

  • Automatic File Detection: Scans source directory for target file types
  • Selective Moving: Only moves files with specified extensions
  • Progress Feedback: Reports each file moved with full path
  • Multiple File Types: Supports text, PDF, and image files
  • Simple Configuration: Easy to modify file types and directories
  • Error Prevention: Uses built-in file operations for reliability
  • Completion Notification: Confirms when all operations are finished

Supported File Types

The script currently handles these file extensions:

  • Text Files: .txt
  • PDF Documents: .pdf
  • Image Files: .png, .jpg, .jpeg

Adding More File Types

To support additional file types, simply modify the file_typesfile_types list:

automatedfilemover.py
file_types = ["txt", "pdf", "png", "jpg", "jpeg", "docx", "xlsx", "mp3", "mp4"]
automatedfilemover.py
file_types = ["txt", "pdf", "png", "jpg", "jpeg", "docx", "xlsx", "mp3", "mp4"]

How It Works

Directory Structure

Before Running:
source/
├── document.txt
├── report.pdf
├── photo.png
├── data.csv      (not moved - not in file_types)
└── script.py     (not moved - not in file_types)
 
destination/
└── (empty)
 
After Running:
source/
├── data.csv      (remains - not in file_types)
└── script.py     (remains - not in file_types)
 
destination/
├── document.txt  (moved)
├── report.pdf    (moved)
└── photo.png     (moved)
Before Running:
source/
├── document.txt
├── report.pdf
├── photo.png
├── data.csv      (not moved - not in file_types)
└── script.py     (not moved - not in file_types)
 
destination/
└── (empty)
 
After Running:
source/
├── data.csv      (remains - not in file_types)
└── script.py     (remains - not in file_types)
 
destination/
├── document.txt  (moved)
├── report.pdf    (moved)
└── photo.png     (moved)

Process Flow

  1. Scan Source: Get list of all files in source directory
  2. Filter by Type: Check each file against target extensions
  3. Move Files: Transfer matching files to destination
  4. Report Progress: Print status for each moved file
  5. Complete: Notify when all operations are finished

Use Cases

  • Download Organization: Automatically sort downloaded files
  • Photo Management: Organize images by moving to specific folders
  • Document Sorting: Separate documents by type or project
  • Cleanup Tasks: Remove clutter from working directories
  • Backup Operations: Move files to backup locations
  • Project Organization: Sort project files into appropriate folders

Next Steps

You can enhance this project by:

  • Adding a GUI interface for directory selection
  • Implementing subdirectory organization by file type
  • Adding file size filtering and duplicate detection
  • Creating scheduled automation with task scheduling
  • Adding undo functionality to reverse moves
  • Implementing regex patterns for complex file matching
  • Adding logging and error handling for failed operations
  • Creating configuration files for custom rules
  • Adding network drive support for remote file management
  • Implementing file compression before moving

Enhanced Version Ideas

automatedfilemover.py
import logging
from datetime import datetime
from pathlib import Path
 
class AdvancedFileMover:
    def __init__(self, source_dir, destination_dir):
        self.source = Path(source_dir)
        self.destination = Path(destination_dir)
        self.setup_logging()
    
    def setup_logging(self):
        logging.basicConfig(
            filename='file_moves.log',
            level=logging.INFO,
            format='%(asctime)s - %(message)s'
        )
    
    def organize_by_type(self):
        # Create subdirectories for each file type
        file_type_map = {
            'txt': 'Documents/Text',
            'pdf': 'Documents/PDF',
            'png': 'Images/PNG',
            'jpg': 'Images/JPEG'
        }
        
        for file_type, subfolder in file_type_map.items():
            target_dir = self.destination / subfolder
            target_dir.mkdir(parents=True, exist_ok=True)
    
    def move_with_conflict_resolution(self, source_file, target_file):
        if target_file.exists():
            # Handle file name conflicts
            counter = 1
            while target_file.exists():
                name = target_file.stem
                extension = target_file.suffix
                target_file = target_file.parent / f"{name}_{counter}{extension}"
                counter += 1
        
        shutil.move(str(source_file), str(target_file))
        logging.info(f"Moved {source_file} to {target_file}")
automatedfilemover.py
import logging
from datetime import datetime
from pathlib import Path
 
class AdvancedFileMover:
    def __init__(self, source_dir, destination_dir):
        self.source = Path(source_dir)
        self.destination = Path(destination_dir)
        self.setup_logging()
    
    def setup_logging(self):
        logging.basicConfig(
            filename='file_moves.log',
            level=logging.INFO,
            format='%(asctime)s - %(message)s'
        )
    
    def organize_by_type(self):
        # Create subdirectories for each file type
        file_type_map = {
            'txt': 'Documents/Text',
            'pdf': 'Documents/PDF',
            'png': 'Images/PNG',
            'jpg': 'Images/JPEG'
        }
        
        for file_type, subfolder in file_type_map.items():
            target_dir = self.destination / subfolder
            target_dir.mkdir(parents=True, exist_ok=True)
    
    def move_with_conflict_resolution(self, source_file, target_file):
        if target_file.exists():
            # Handle file name conflicts
            counter = 1
            while target_file.exists():
                name = target_file.stem
                extension = target_file.suffix
                target_file = target_file.parent / f"{name}_{counter}{extension}"
                counter += 1
        
        shutil.move(str(source_file), str(target_file))
        logging.info(f"Moved {source_file} to {target_file}")

Configuration Options

Custom Directory Paths

automatedfilemover.py
# Modify these paths as needed
source = "/path/to/your/source/directory/"
destination = "/path/to/your/destination/directory/"
 
# Or use command line arguments
import sys
if len(sys.argv) > 2:
    source = sys.argv[1]
    destination = sys.argv[2]
automatedfilemover.py
# Modify these paths as needed
source = "/path/to/your/source/directory/"
destination = "/path/to/your/destination/directory/"
 
# Or use command line arguments
import sys
if len(sys.argv) > 2:
    source = sys.argv[1]
    destination = sys.argv[2]

File Type Categories

automatedfilemover.py
# Organize by categories
document_types = ["txt", "pdf", "doc", "docx"]
image_types = ["png", "jpg", "jpeg", "gif", "bmp"]
video_types = ["mp4", "avi", "mov", "mkv"]
audio_types = ["mp3", "wav", "flac", "aac"]
automatedfilemover.py
# Organize by categories
document_types = ["txt", "pdf", "doc", "docx"]
image_types = ["png", "jpg", "jpeg", "gif", "bmp"]
video_types = ["mp4", "avi", "mov", "mkv"]
audio_types = ["mp3", "wav", "flac", "aac"]

Error Handling Improvements

automatedfilemover.py
import os
import shutil
import logging
 
def safe_file_move():
    try:
        for file in files:
            source_path = os.path.join(source, file)
            destination_path = os.path.join(destination, file)
            
            # Check if source file exists
            if not os.path.exists(source_path):
                print(f"Warning: {file} not found in source")
                continue
            
            # Check if destination already exists
            if os.path.exists(destination_path):
                print(f"Warning: {file} already exists in destination")
                continue
            
            # Perform the move
            shutil.move(source_path, destination_path)
            print(f"Successfully moved {file}")
            
    except PermissionError:
        print("Error: Permission denied. Check file permissions.")
    except Exception as e:
        print(f"Unexpected error: {e}")
automatedfilemover.py
import os
import shutil
import logging
 
def safe_file_move():
    try:
        for file in files:
            source_path = os.path.join(source, file)
            destination_path = os.path.join(destination, file)
            
            # Check if source file exists
            if not os.path.exists(source_path):
                print(f"Warning: {file} not found in source")
                continue
            
            # Check if destination already exists
            if os.path.exists(destination_path):
                print(f"Warning: {file} already exists in destination")
                continue
            
            # Perform the move
            shutil.move(source_path, destination_path)
            print(f"Successfully moved {file}")
            
    except PermissionError:
        print("Error: Permission denied. Check file permissions.")
    except Exception as e:
        print(f"Unexpected error: {e}")

Automation Ideas

  • Schedule Regular Runs: Use cron (Linux/Mac) or Task Scheduler (Windows)
  • Watch Directory Changes: Use watchdogwatchdog library for real-time monitoring
  • Email Notifications: Send reports when file moves are completed
  • Integration: Combine with other scripts for complete workflow automation

Security Considerations

  • Path Validation: Ensure source and destination paths are safe
  • Permission Checks: Verify read/write access before operations
  • Backup Creation: Create backups before moving important files
  • Logging: Maintain records of all file operations

Educational Value

This project teaches:

  • File System Operations: Working with directories and files
  • Path Manipulation: Understanding file paths and navigation
  • Iteration and Conditionals: Processing lists and making decisions
  • String Operations: Working with file extensions and names
  • Error Prevention: Safe file handling practices

Real-World Applications

  • System Administration: Automated file organization on servers
  • Personal Productivity: Organizing downloads and documents
  • Data Processing: Sorting data files for analysis workflows
  • Content Management: Organizing media files and assets
  • Backup Systems: Automated file archiving and organization

Conclusion

In this project, we learned how to create an Automated File Mover using Python’s built-in file system modules. We explored directory operations, file manipulation, and automation techniques. This script demonstrates practical applications of programming in everyday file management tasks and provides a foundation for more complex automation projects. The ability to programmatically organize files is valuable for both personal productivity and professional system administration. To find more projects like this, you can visit Python Central Hub.

Was this page helpful?

Let us know how we did