Python:将钩子拷贝到所有文件夹下

import os
import shutil

def copy_images_to_all_folders():
    # 获取当前工作目录
    current_dir = os.getcwd()
    
    # 要拷贝的图片文件名
    image_files = ['1.png', '2.png']
    
    # 检查源图片文件是否存在
    for image_file in image_files:
        source_path = os.path.join(current_dir, image_file)
        if not os.path.exists(source_path):
            print(f"错误:源文件 {image_file} 不存在于当前目录中")
            return False
    
    # 计数器
    folders_count = 0
    
    # 遍历当前目录及其所有子目录
    for root, dirs, files in os.walk(current_dir):
        # 跳过当前目录本身(只处理子文件夹)
        if root == current_dir:
            continue
            
        # 拷贝图片到当前遍历到的文件夹
        for image_file in image_files:
            source_path = os.path.join(current_dir, image_file)
            destination_path = os.path.join(root, image_file)
            
            # 如果目标文件已存在,可以选择跳过或覆盖
            if os.path.exists(destination_path):
                print(f"文件 {image_file} 已存在于 {root},跳过")
                continue
            
            try:
                shutil.copy2(source_path, destination_path)
                print(f"已拷贝 {image_file} 到 {root}")
            except Exception as e:
                print(f"拷贝 {image_file} 到 {root} 时出错: {e}")
        
        folders_count += 1
    
    print(f"\n完成!已处理 {folders_count} 个文件夹")
    return True

if __name__ == "__main__":
    copy_images_to_all_folders()
 
Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐