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

Python合并多个Excel文件报list类型路径ValueError错误如何解决

问题原因与解决方案

报错直接原因

ValueError: Invalid file path or buffer object type: <class 'list'>

该报错是因为你调用pd.read_excel(args.data)时,args.data是你用nargs="+"接收的多文件参数,本身是列表类型,但pd.read_excel()只支持传入单个文件路径/文件对象,不支持直接传列表。

代码存在的其他问题

  • 输出文件名格式化错误:"%s_%s.xlsx"%(args.out)有2个占位符,但只传了1个参数,运行会触发类型错误
  • 调用argparse.FileType会直接打开传入的文件返回文件对象,但pd.read_excel读取Excel不需要提前打开,直接传路径更稳妥
  • 循环逻辑错误:嵌套的for line in filename是逐行读取文件内容,完全不符合读取Excel表格的需求
  • 写入逻辑错误:直接调用to_excel()会覆盖原有文件,无法实现追加数据的效果
  • 读取逻辑错误:循环里没有读取当前遍历到的单个文件,反而重复读整个参数列表

修正后的代码

import pandas as pd
import argparse
import os

parser = argparse.ArgumentParser(description="extract data from machine")
# 改为接收文件路径字符串,不提前打开
parser.add_argument("-d","--data", dest="data", required=True, action="store", type=str, nargs="+",
                     help="the excel file you want to analysis")
parser.add_argument("-o","--outFileNamePrefix",action="store",default="foo",dest="out",
                    help="the output file name")
args = parser.parse_args()

# 初始化输出表
output = pd.DataFrame(columns=['Target','Sample','SQ Mean', 'SQ Std. Dev'])
# 修正文件名格式化,可按需调整后缀规则
out_path = f"{args.out}_merged.xlsx"
output.to_excel(out_path, index=False)

# 遍历所有输入的Excel文件
for file_path in args.data:
    # 读取单个Excel文件,多sheet需自行指定sheet_name参数
    df = pd.read_excel(file_path)
    # 筛选匹配目标结构的列,源表列名不一致时可自行做映射调整
    df = df[['Target','Sample','SQ Mean', 'SQ Std. Dev']]
    # 追加写入,不重复写表头
    with pd.ExcelWriter(out_path, mode='a', if_sheet_exists='overlay', engine='openpyxl') as writer:
        df.to_excel(writer, index=False, header=False, startrow=writer.sheets['Sheet1'].max_row)

运行注意事项

  • 需提前安装依赖:pip install openpyxl,追加写入Excel需要该引擎支持
  • 若pandas版本低于1.4,if_sheet_exists参数不可用,可先把所有文件数据合并到同一个DataFrame后再一次性写入输出文件

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:45:04