Brain II

Site Tools


start:knowledge:computer_science:programming

<< Back

Programming

Background

Languages

Artistic Languages

Hydra
Processing

C++

Lua

Pyhon

Copy all images from folder and child folders

  1. import os
  2. import shutil
  3. def copy_images_and_parent_folder(source_folder, destination_folder):
  4. # Create the destination folder if it doesn't exist
  5. if not os.path.exists(destination_folder):
  6. os.makedirs(destination_folder)
  7. # Walk through the source folder and its subfolders
  8. for root, dirs, files in os.walk(source_folder):
  9. for file in files:
  10. # Check if the file is an image (based on file extension)
  11. if file.lower().endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
  12. source_path = os.path.join(root, file)
  13. destination_path = os.path.join(destination_folder, file)
  14. shutil.copy2(source_path, destination_path)
  15. print(f"Copied {file} to {destination_folder}")
  16. # Copy the parent folder from the source to the destination
  17. parent_folder = os.path.dirname(source_folder)
  18. parent_folder_name = os.path.basename(parent_folder)
  19. destination_parent_folder = os.path.join(destination_folder, parent_folder_name)
  20. if not os.path.exists(destination_parent_folder):
  21. shutil.copytree(parent_folder, destination_parent_folder)
  22. print(f"Copied parent folder: {parent_folder_name}")
  23. # Set the source folder path (change to the desired folder)
  24. source_folder_path = "/path/to/your/source/folder"
  25. # Set the destination folder path (create a new folder or use an existing one)
  26. destination_folder_path = "/path/to/your/destination/folder"
  27. # Call the function to copy images and the parent folder
  28. copy_images_and_parent_folder(source_folder_path, destination_folder_path)
  29. }();

Replace “/path/to/your/source/folder” with the actual path to the folder containing your images, and “/path/to/your/destination/folder” with the desired destination folder. This script will copy image files source to the destination.

Git

start/knowledge/computer_science/programming.txt · Last modified: 2025/03/24 09:57 by florian