How to Copy Different Types of Images from One Folder to Another Using Python?

Estimated read time 3 min read

To copy different types of images from one folder to another using Python, you can use the os and shutil modules to iterate over the files in the source folder, identify the image files, and copy them to the destination folder. Here’s an example:

import os
import shutil

# Replace 'source_directory_path' with the path to the directory containing the image files you want to copy
source_directory_path = 'path/to/source/directory'

# Replace 'destination_directory_path' with the path to the directory where you want to copy the image files
destination_directory_path = 'path/to/destination/directory'

# Define a list of image file extensions you want to copy
image_extensions = ['.jpg', '.jpeg', '.png', '.gif']

# Iterate over the files in the source directory
for filename in os.listdir(source_directory_path):
    # Get the file extension
    extension = os.path.splitext(filename)[1]
    # Check if the file is an image file
    if extension.lower() in image_extensions:
        # Build the source and destination file paths
        source_file_path = os.path.join(source_directory_path, filename)
        destination_file_path = os.path.join(destination_directory_path, filename)
        # Copy the file from the source path to the destination directory
        shutil.copy(source_file_path, destination_file_path)

In the above code, we first import the os and shutil modules. We then specify the path to the directory containing the image files we want to copy (source_directory_path) and the path to the directory where we want to copy the image files (destination_directory_path).

We define a list of image file extensions we want to copy (image_extensions). This list contains the extensions .jpg, .jpeg, .png, and .gif, but you can modify it to include other image file extensions as needed.

We use the os.listdir method to iterate over the files in the source directory. For each file, we get the file extension using the os.path.splitext method, and check if the file extension is in the list of image file extensions. If it is, we build the source and destination file paths using the os.path.join method and copy the file from the source path to the destination directory using the shutil.copy method.

Note that this code assumes that the image files are all in the root of the source directory and not in any subdirectories. If the image files are in subdirectories, you will need to modify the code to handle those cases.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply