汇总文件Python脚本

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
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值