python递归提取文件夹下指定类型的文件到某个文件夹
递归提取文件夹下指定类型的文件到某个文件夹
importosimportshutildefcopy_files_by_type(source_dir,target_dir,file_extensions):""" 递归遍历源目录,将指定类型的文件复制到目标目录。 :param source_dir: 源目录路径 :param target_dir: 目标目录路径 :param file_extensions: 文件扩展名列表,如 ['.txt', '.py'] """# 确保目标目录存在os.makedirs(target_dir,exist_ok=True)# 遍历源目录forroot,dirs,filesinos.walk(source_dir):forfileinfiles:# 检查文件扩展名是否匹配ifany(file.endswith(ext)forextinfile_extensions):source_path=os.path.join(root,file)target_path=os.path.join(target_dir,file)# 如果目标目录中已存在同名文件,则重命名counter=1original_target_path=target_pathwhileos.path.exists(target_path):name,ext=os.path.splitext(original_target_path)target_path=f"{name}_{counter}{ext}"counter+=1# 复制文件shutil.copy2(source_path,target_path)print(f"Copied:{source_path}->{target_path}")if__name__=="__main__":# 示例输入输出路径source_directory="C:\\Users\\Luke\\Desktop\\image"target_directory="C:\\Users\\Luke\\Desktop\\image"extensions_input='.jpg,.jpeg,.heic'# 自定义文件类型file_extensions=[ext.strip()forextinextensions_input.split(",")ifext.strip()]copy_files_by_type(source_directory,target_directory,file_extensions)