Python开发求助:编写多文件夹下随机保留部分图片的脚本
Hey there! I get that starting out with Python can feel overwhelming, so I’ve put together a straightforward, well-commented script that’ll do exactly what you need. It uses only Python’s built-in libraries (no extra installs required!) and includes clear explanations so you follow along with what each part does.
First, a Critical Warning
Always back up your images first! This script deletes files, and while it’s designed to be safe, accidents can happen. Copy your folders to a separate location before running anything—better safe than sorry!
The Script
Here’s the code—copy-paste this into a file named keep_random_images.py and tweak the settings to match your needs:
import os import random # -------------------------- # 🔧 Configure these settings! # -------------------------- ROOT_FOLDER = "/path/to/your/root/folder" # Replace with your actual folder path # Option 1: Keep a percentage of images (0.3 = 30%) KEEP_RATIO = 0.3 # Option 2: Keep a fixed number of images per folder (uncomment this, comment KEEP_RATIO above) # KEEP_COUNT = 10 # Which image formats should we process? Add/remove as needed IMAGE_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.gif', '.bmp') def process_folder(folder_path): # Grab all image files in the current folder image_files = [] for filename in os.listdir(folder_path): # Check if it's a file and matches our image extensions (case-insensitive) if filename.lower().endswith(IMAGE_EXTENSIONS): file_path = os.path.join(folder_path, filename) if os.path.isfile(file_path): image_files.append(filename) if not image_files: print(f"⚠️ No images found in {folder_path} — skipping.") return # Calculate how many images to keep if 'KEEP_RATIO' in locals(): # Ensure we keep at least 1 image even if the ratio gives 0 num_to_keep = max(1, int(len(image_files) * KEEP_RATIO)) else: # Don't try to keep more images than exist num_to_keep = min(KEEP_COUNT, len(image_files)) # Randomly select which images to keep images_to_keep = random.sample(image_files, num_to_keep) images_to_delete = [img for img in image_files if img not in images_to_keep] print(f"\n📂 Processing {folder_path}:") print(f"Total images: {len(image_files)} | Keeping: {num_to_keep} | Deleting: {len(images_to_delete)}") # Delete the unwanted images for img in images_to_delete: full_path = os.path.join(folder_path, img) try: os.remove(full_path) print(f"✅ Deleted: {full_path}") except Exception as e: print(f"❌ Failed to delete {full_path}: {str(e)}") # Walk through all folders and subfolders under the root for root, dirs, files in os.walk(ROOT_FOLDER): process_folder(root) print("\n🎉 All folders processed successfully!")
How to Use This
Update the settings:
- Replace
ROOT_FOLDERwith the path to your main folder (the one holding all your image subfolders). Examples:- Windows:
C:/Users/YourName/Pictures/MyPhotoFolders - Mac/Linux:
/home/yourname/pictures/my_photo_folders
- Windows:
- Choose either
KEEP_RATIO(percentage) orKEEP_COUNT(fixed number) by uncommenting the one you want and commenting the other. - Add/remove image extensions in
IMAGE_EXTENSIONSif you need to include formats like.webpor exclude others.
- Replace
Run the script:
- Open your terminal/command prompt, navigate to where you saved the
.pyfile, and run:python keep_random_images.py
- Open your terminal/command prompt, navigate to where you saved the
Extra Tips for Beginners
- Test first: If you’re nervous, create a small test folder with duplicate images and run the script on that first to see how it works.
- Avoid nested folders (if you want): If you only want to process direct subfolders of your root (not nested ones), replace the
os.walkloop with this:for folder_name in os.listdir(ROOT_FOLDER): folder_path = os.path.join(ROOT_FOLDER, folder_name) if os.path.isdir(folder_path): process_folder(folder_path) - Permissions: If you get a "permission denied" error, make sure you have permission to modify files in the target folders.
内容的提问来源于stack exchange,提问作者Vannaro

