基于Python批量删除文件和批量增加文件
一、为什么写这么一个程序
其实原因也是很简单的,我去网上下载了一个文件夹,里面太多别人的文件了,我不喜欢,所以我就写了这么一个代码。
二、安装Python和vscode
先安装Python在安装vscode
Python安装
vscode的安装
三、源码
import os
import shutil# 配置路径
parent_folder = r"文件路径" # 父文件夹路径
source_file_c = r"文件路径" # 已有的文件c路径
files_to_delete = ["要删除的文件名","要删除的文件名"] # 要删除的文件名# 1. 批量删除文件a和文件b
for root, dirs, files in os.walk(parent_folder):for file in files:if file in files_to_delete:file_path = os.path.join(root, file)try:os.remove(file_path)print(f"已删除:{file_path}")except Exception as e:print(f"删除失败 {file_path}: {e}")# 2. 批量复制文件c到所有子文件夹
for root, dirs, files in os.walk(parent_folder):for dir in dirs:dest_path = os.path.join(root, dir, os.path.basename(source_file_c))try:shutil.copy2(source_file_c, dest_path) # 保留文件属性print(f"已复制到:{dest_path}")except Exception as e:print(f"复制失败到 {dest_path}: {e}")
四、源码下载
链接:https://pan.quark.cn/s/223a98d02dd9