Copy Image Files Between Directories in Python

Prompt

Write a function to copy all image files from a directory to a specified folder
Python

Result

import os
import shutil

def copy_images(source_dir, destination_dir):
    """
    Copy all image files from a directory to a specified folder.

    Args:
        source_dir (str): The path to the source directory.
        destination_dir (str): The path to the destination directory.

    Returns:
        None
    """
    # Check if the source directory exists
    if not os.path.exists(source_dir):
        print(f"Source directory '{source_dir}' does not exist.")
        return

    # Check if the destination directory exists, create it if not
    if not os.path.exists(destination_dir):
        os.makedirs(destination_dir)

    # Get a list of all files in the source directory
    files = os.listdir(source_dir)

    # Iterate over each file in the source directory
    for file in files:
        # Get the full path of the file
        file_path = os.path.join(source_dir, file)

        # Check if the file is an image file
        if os.path.isfile(file_path) and file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
            # Copy the file to the destination directory
            shutil.copy(file_path, destination_dir)

    print("Image files copied successfully.")

# Example usage
copy_images("path/to/source/directory", "path/to/destination/directory")
Python

This function takes two arguments: source_dir and destination_dir. It first checks if the source directory exists. If not, it prints an error message and returns. Then, it checks if the destination directory exists. If not, it creates the directory.

Next, it gets a list of all files in the source directory. It iterates over each file and checks if it is an image file by checking its extension. If it is, it copies the file to the destination directory using the shutil.copy() function.

Finally, it prints a success message when all image files have been copied.