You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发求助:编写多文件夹下随机保留部分图片的脚本

Randomly Keep Subset of Images Across Multiple Folders (Python for Beginners)

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

  1. Update the settings:

    • Replace ROOT_FOLDER with 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
    • Choose either KEEP_RATIO (percentage) or KEEP_COUNT (fixed number) by uncommenting the one you want and commenting the other.
    • Add/remove image extensions in IMAGE_EXTENSIONS if you need to include formats like .webp or exclude others.
  2. Run the script:

    • Open your terminal/command prompt, navigate to where you saved the .py file, and run:
      python keep_random_images.py
      

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.walk loop 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 16:27:49