Python脚本,将所有文件夹下面的文件汇总到同一个文件夹。以下是一个简单的脚本示例,它会遍历指定目录及其子目录中的所有文件,并将这些文件复制到一个目标文件夹中。
import os
import shutil
def consolidate_files(src_directory, dest_directory):
# 如果目标文件夹不存在,创建它
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
# 遍历源目录及其子目录中的所有文件
for root, dirs, files in os.walk(src_directory):
for file in files:
file_path = os.path.join(root, file)
dest_path = os.path.join(dest_directory, file)
# 处理文件重名的情况
if os.path.exists(dest_path):
base, extension = os.path.splitext(file)
counter = 1
while os.path.exists(dest_path):
dest_path = os.path.join(dest_directory, f"{base}_{counter}{extension}")
counter += 1
# 复制文件到目标文件夹
shutil.copy2(file_path, dest_pa