You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:如何用Python按生成的日期列表批量复制指定文件

问题描述

我有一个存放Power Automate生成文件的目录,文件按拉取日期命名。已通过Python的模式匹配实现文件移动,但需改为动态逻辑:依据脚本生成的前10天日期列表res,仅复制对应日期的文件到临时目录,后续用于生成DataFrame及BI报表汇总。当前代码使用固定匹配模式mastdirectory + "/01*"可运行,但无法动态匹配日期列表;尝试os.scandir循环匹配失败,寻求解决方案。

现有代码

import pandas as pd
import os
import time
from asyncio import sleep
import win32com.client
import time
import glob
from datetime import datetime as dt
from datetime import timedelta
import shutil as shutil

mastdirectory = r"C:/Users/bowergr/OneDrive - Company Name/MAST Pulls/History/MAST Library"
dir_cache = r"C:/Users/Bowergr/OneDrive - Company Name/MAST Pulls/Tracking/QMS/Data_Cache/Mast_Transfer//"

today = dt.today()
today_date, today_time = today.date(), today.time()
D = 10

print("当前日期: ", today_date.strftime('%m-%d-%Y'))
today_date_f = today_date.strftime('%m-%d-%Y')
daterange = today_date + timedelta(days=-10)
daterange_f = daterange.strftime('%m-%d-%Y')
print("日期范围: (当前日期: ", today_date.strftime('%m-%d-%Y'), "), (起始日期:", daterange_f, ")")

res = []
for day in range(D):
    date = (today_date + timedelta(days = -day)).strftime('%m-%d-%Y')
    res.append(date)
print("待处理MAST日期列表: " + str(res))

# 原固定匹配逻辑
pattern = mastdirectory + "/01*"
for file in glob.iglob(pattern, recursive=True):
    file_name = os.path.basename(file)
    shutil.copyfile(file, dir_cache + "_" + file_name)
    print('已移动:', file)

相关示例

  • 生成的日期列表res示例:
    ['01-12-2023', '01-11-2023', '01-10-2023', '01-09-2023', '01-08-2023', '01-07-2023', '01-06-2023', '01-05-2023', '01-04-2023', '01-03-2023']
    
  • 目标文件名示例:01-12-2023.xlsx、01-11-2023.xlsx
解决方案

提供两种可行的修改方案,可根据目录文件数量选择:

方案1:按日期列表构造文件路径(直观易维护)

遍历日期列表res,为每个日期构造完整的源文件路径,检查文件存在后直接复制。逻辑简单,适合文件数量较少的场景。

替换原代码中pattern及后续循环部分为以下代码:

for date in res:
    # 构造源文件完整路径
    source_path = os.path.join(mastdirectory, f"{date}.xlsx")
    # 检查文件是否存在
    if os.path.exists(source_path):
        file_name = os.path.basename(source_path)
        # 构造目标文件路径(保留原命名规则,前缀加下划线)
        dest_path = os.path.join(dir_cache, f"_{file_name}")
        shutil.copyfile(source_path, dest_path)
        print('复制完成:', source_path)
    else:
        print(f"未找到对应文件: {source_path}")

方案2:遍历目录过滤匹配(高效适合大量文件)

先将日期列表转为集合(集合的成员查找效率远高于列表),再遍历源目录所有文件,提取文件名中的日期部分(去掉后缀),判断是否在日期集合中,符合条件则复制。这种方法只需遍历一次目录,效率更高。

替换原代码中pattern及后续循环部分为以下代码:

# 将日期列表转为集合,提升查找速度
target_dates = set(res)

# 遍历源目录
with os.scandir(mastdirectory) as entries:
    for entry in entries:
        # 仅处理xlsx文件
        if entry.is_file() and entry.name.endswith('.xlsx'):
            # 提取文件名中的日期(去掉.xlsx后缀)
            file_date = os.path.splitext(entry.name)[0]
            # 判断日期是否在目标列表中
            if file_date in target_dates:
                dest_path = os.path.join(dir_cache, f"_{entry.name}")
                shutil.copyfile(entry.path, dest_path)
                print('复制完成:', entry.path)

原os.scandir失败可能原因

  1. 未正确提取文件名中的日期部分(比如没处理.xlsx后缀)
  2. 路径拼接错误,导致目标路径无效
  3. 未限制文件类型,误处理了非xlsx文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:10:34