网上可以搜到很多方式,有的好使,有的不好使,亲测如下脚本可用,并可达到我想要的效果,只将多个文件夹里的文件拷贝到一个文件夹中,不拷贝文件夹本身,如果需要文件夹也拷贝打开注释行即可
import os
import shutil
import glob# 源文件夹路径
source_folder = "C:/Users/Desktop/test folder/Source"# 目标文件夹路径
destination_folder = "C:/Users/Desktop/test folder/destination"# 定义一个递归函数,用于遍历文件夹内的所有文件和子文件夹
def merge_files(source, destination):for filename in os.listdir(source):# 构建源文件的完整路径source_file = os.path.join(source, filename)# 构建目标文件的完整路径#destination_file = os.path.join(destination, filename)# 判断文件是否为普通文件if os.path.isfile(source_file):# 调用shutil模块的函数将文件复制到目标文件夹内shutil.copy(source_file, destination)# 判断文件是否为文件夹,并递归调用函数处理子文件夹内的文件elif os.path.isdir(source_file):# 创建对应的子文件夹#os.makedirs(destination_file, exist_ok=True)# 调用递归函数处理子文件夹内的文件merge_files(source_file, destination)# 调用递归函数开始合并文件夹
merge_files(source_folder, destination_folder)