筛出文件指定比例的文件

import os
import shutil
import random

# 设置源目录和目标目录
source_dir = r"G:\trian"
target_dir = r"G:\test"
move_percent = 10  # 百分比

# 遍历一级子文件夹
for subfolder in os.listdir(source_dir):
    subfolder_path = os.path.join(source_dir, subfolder)
    if not os.path.isdir(subfolder_path):
        continue  # 跳过非文件夹项

    # 收集该子文件夹下所有文件(递归)
    all_files = []
    for root, _, files in os.walk(subfolder_path):
        for file in files:
            full_path = os.path.join(root, file)
            all_files.append(full_path)

    # 随机选取百分比文件
    total = len(all_files)
    if total == 0:
        continue

    move_count = max(1, int(total * move_percent / 100))
    selected_files = random.sample(all_files, move_count)

    # 执行移动
    for file_path in selected_files:
        rel_path = os.path.relpath(file_path, source_dir)
        dest_path = os.path.join(target_dir, rel_path)
        os.makedirs(os.path.dirname(dest_path), exist_ok=True)
        shutil.move(file_path, dest_path)
        print(f"Moved: {file_path} → {dest_path}")

print(f"\n✅ 每个子文件夹已随机移动约 {move_percent}% 文件。")

❤️ 转载文章请注明出处,谢谢!❤️