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

Python实现XLSX数据复制到子文件夹最新XLSM文件报错求助

问题描述

需要将源文件夹中的.xlsx文件数据复制到对应子文件夹中最新的.xlsm目标文件中:

  • 源文件路径:c:/users/me/afolder/sourcefolder/,命名格式如ABC_Report.xlsx、DEF_Report.xlsx
  • 目标文件存放在对应子文件夹,比如c:/users/me/somefolder/destination/ABC/下有多个版本的.xlsm文件,需要依据文件最新修改时间选择最新的那个(而非文件名)
  • 当前代码报错:有时提示latest_file未定义,用glob.glob时出现[WinError 2]系统找不到指定文件'C'的错误

附上原代码:

from glob import glob
import openpyxl
from openpyxl import load_workbook

def copy_data(src_file: str, dst_file: str) -> None:
# open files
  ws_src = load_workbook(src_file)["src sheet"]
  wb_dst = load_workbook(dst_file, keep_vba=True)
  ws_dst = wb_dst["dest sheet"]

  # configuration
  start_row_src = 2       
  start_row_dst = 10      
  rows2copy = 100000

  # copy data from src_file to dst_file
   input_offset = start_row_dst - start_row_src
   for i in range(start_row_src, rows2copy):
      ws_dst[f"A{i}"].value = ws_src[f"A{i + input_offset}"].value
      ws_dst[f"B{i}"].value = ws_src[f"B{i + input_offset}"].value

    # save the modifications
    wb_dst.save(dst_file)

   #This bottom part of my code that doesn't work the top part works just fine
   # Source filepath
   src_dir_path = = "C:/users/me/afolder/sourcefolder/"

# iterate over all excel files found in source path
workbooks = list(Path(src_dir_path).glob("*.xlsx")) 
for src in workbooks:
        dst_dir_path = "C:/Users/me/somefolder/destinationfolder/{f}/".format(f=(src.stem.replace("_Report", "")))
        #Iterate over files in destination folder to get most recent file
        list_of_files = list(Path(dst_dir_path).glob("*.xlsm"))
for files in list_of_files:
    latest_file = max(files, key=os.path.getmtime)
lfile = os.path.basename(latest_file[3:15])
dst = dst_dir_path + os.path.basename(src).replace("_Report.xlsx", lfile )
copy_data(src, dst)
代码问题分析
  1. 语法错误:src_dir_path = = "..."多了一个等号,直接触发语法报错
  2. 依赖缺失:使用了Path但未导入pathlib.Path,使用os.path但未导入os模块
  3. 缩进混乱:Python对缩进敏感,copy_data函数内、底部逻辑的缩进都不符合规则,导致代码执行逻辑混乱
  4. 循环逻辑错误:外层遍历源文件的循环结束后才处理目标文件列表,导致list_of_files仅保留最后一个源文件对应的内容;且for files in list_of_files完全多余,max可直接作用于文件列表
  5. 路径处理错误:latest_file[3:15]是对Path对象做切片,触发类型错误;手动截取文件名的逻辑无意义,直接用latest_file.name即可获取文件名
  6. 变量作用域问题:latest_file在循环外引用,若目标文件夹无.xlsm文件会导致未定义错误
  7. 数据复制逻辑错误:原代码的行偏移方向搞反,导致目标行和源行对应错误
修复后的代码
from pathlib import Path
import os
from openpyxl import load_workbook

def copy_data(src_file: str, dst_file: str) -> None:
    # 打开文件
    wb_src = load_workbook(src_file)
    ws_src = wb_src["src sheet"]
    wb_dst = load_workbook(dst_file, keep_vba=True)
    ws_dst = wb_dst["dest sheet"]

    # 配置参数
    start_row_src = 2       
    start_row_dst = 10      
    rows2copy = 100000

    # 计算行偏移量:目标起始行 - 源起始行
    input_offset = start_row_dst - start_row_src

    # 优化:仅复制源文件中有数据的行,避免空循环
    max_src_row = ws_src.max_row
    end_row = min(start_row_src + rows2copy - 1, max_src_row)
    
    # 复制A、B列数据
    for i in range(start_row_src, end_row + 1):
        ws_dst[f"A{i + input_offset}"].value = ws_src[f"A{i}"].value
        ws_dst[f"B{i + input_offset}"].value = ws_src[f"B{i}"].value

    # 保存修改
    wb_dst.save(dst_file)

# 源文件路径
src_dir_path = Path("C:/users/me/afolder/sourcefolder/")

# 遍历所有源.xlsx文件
for src in src_dir_path.glob("*.xlsx"):
    # 提取目标文件夹名称(如ABC_Report.xlsx -> ABC)
    folder_name = src.stem.replace("_Report", "")
    dst_dir_path = Path(f"C:/Users/me/somefolder/destinationfolder/{folder_name}/")

    # 获取目标文件夹下所有.xlsm文件
    list_of_files = list(dst_dir_path.glob("*.xlsm"))
    if not list_of_files:
        print(f"警告:目标文件夹 {dst_dir_path} 中未找到.xlsm文件,跳过")
        continue

    # 按修改时间获取最新文件
    latest_file = max(list_of_files, key=os.path.getmtime)

    # 执行数据复制
    copy_data(str(src), str(latest_file))
修复说明
  • 补全了缺失的Path和os模块导入
  • 修正了语法错误和缩进问题
  • 优化数据复制逻辑:只复制源文件中有数据的行,同时修正了行偏移方向错误
  • 增加空文件列表判断,避免latest_file未定义的错误
  • 使用Path对象原生方法处理路径,避免手动拼接导致的路径错误
  • 移除冗余循环,直接通过max函数获取最新修改的文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 20:25:25