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

Python使用Pandas批量合并Excel时os.listdir报参数类型错误如何解决

问题原因排查
  • 核心错误来自第5行的变量赋值逻辑错误:pd.read_excel()的返回值是表格对象DataFrame,你把这个对象赋值给data_location后,传给要求输入路径字符串的os.listdir(),自然触发类型不匹配报错,和报错提示的not DataFrame描述完全对应。
  • 次要隐藏问题:路径拼接直接用+容易出现分隔符缺失错误,推荐用os.path.join()做路径拼接,兼容性更好。
修正方案

根据你的使用场景选择对应修正代码即可:

场景1:所有待处理Excel文件存放在同一个文件夹下

直接把data_location改为你存放Excel的文件夹路径即可:

import os
import pandas as pd

# 此处替换为你存放所有待处理Excel的文件夹路径
data_location = r"C:\Users\barış\Desktop\待处理Excel文件夹"
desired_headings = ["Valuable Information"]
df_total = pd.DataFrame(columns=desired_headings)

for file in os.listdir(data_location):
    # 过滤只读取xlsx格式文件,避免读取到系统隐藏文件报错
    if file.endswith(".xlsx"):
        full_path = os.path.join(data_location, file)
        df_file = pd.read_excel(full_path)
        selected_columns = df_file.loc[:, desired_headings]
        df_total = pd.concat([selected_columns, df_total], ignore_index=True)

# 导出时取消默认的索引列
df_total.to_excel("ValuableInformation.xlsx", index=False)

场景2:y2.xlsx中存储的是所有待处理Excel的路径列表

如果你的y2.xlsx第一列存的是各个待处理Excel的完整路径,用以下修正代码:

import os
import pandas as pd

# 读取路径存储表,假设路径保存在第一列
path_list = pd.read_excel(r"C:\Users\barış\Desktop\y2.xlsx").iloc[:,0].tolist()
desired_headings = ["Valuable Information"]
df_total = pd.DataFrame(columns=desired_headings)

for file_path in path_list:
    if os.path.exists(file_path) and file_path.endswith(".xlsx"):
        df_file = pd.read_excel(file_path)
        selected_columns = df_file.loc[:, desired_headings]
        df_total = pd.concat([selected_columns, df_total], ignore_index=True)

df_total.to_excel("ValuableInformation.xlsx", index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:48:05