You need to enable JavaScript to run this app. Python使用shutil.copy实现多路径下指定PDF文件批量复制问题
优惠活动
大模型
产品
解决方案
定价
更多

Python使用shutil.copy实现多路径下指定PDF文件批量复制问题

修正后可运行实现方案

原有代码核心问题

  • 用zip匹配长度不一致的客户列表、项目编号列表,会导致John、Peter对应的项目编号错位
  • pdf格式判断逻辑错误,字符串和布尔值对比永远不成立
  • 未提前创建目标文件夹,路径不存在时会触发复制失败
  • 文件筛选逻辑未放在客户循环内部,无法对应每个客户的源、目标路径

完整可运行代码

import os
import shutil

def copyFiles():
    # 用字典维护正确的客户-项目编号对应关系,避免配对错误
    cust_proj_map = {
        'Joe': '010',
        'Bob': '016',
        'Mark': '018',
        'John': '016',
        'Peter': '016'
    }
    
    for cust, num in cust_proj_map.items():
        # 初始化源路径、目标路径
        source = f'C:/Users/Desktop/Automation_Testing/Live_{num} ({cust})/01_Docs_Issued/'
        dest = f'C:/Users/Desktop/Automation_Testing/new_{cust}/Data/'

        # 源路径不存在时替换为父级客户Bob
        if not os.path.exists(source):
            source = source.replace(cust, 'Bob')
        
        # 二次校验源路径是否存在,避免异常报错
        if not os.path.exists(source):
            print(f"警告:{cust}对应的源路径{source}不存在,跳过处理")
            continue
        
        # 自动创建目标路径,已存在则不报错
        os.makedirs(dest, exist_ok=True)

        # 遍历筛选符合要求的文件并复制
        for file_name in os.listdir(source):
            # 同时满足:文件名包含INVOICE、后缀为pdf
            if 'INVOICE' in file_name.upper() and file_name.lower().endswith('.pdf'):
                src_file = os.path.join(source, file_name)
                dest_file = os.path.join(dest, file_name)
                shutil.copy(src_file, dest_file)
                print(f"已完成复制:{src_file} -> {dest_file}")

# 执行函数
if __name__ == "__main__":
    copyFiles()

关键修改说明

  • 替换列表配对逻辑为字典映射,彻底避免客户和项目编号匹配错误的问题
  • 合并文件筛选条件,直接判断文件名后缀,删除错误的布尔值对比逻辑
  • 增加os.makedirs逻辑自动生成目标路径,解决路径不存在导致的复制失败问题
  • 增加源路径二次校验逻辑,避免替换为Bob后路径仍不存在的异常
  • 所有文件处理逻辑收拢在客户循环内部,保证源路径和对应客户的目标路径一一匹配

内容的提问来源于stack exchange,提问作者Craig Emslie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.13 21:06:01