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

Python实现多CSV数据追加至已有Excel文件的问题排查

问题分析与修复方案

核心问题拆解

  • ExcelWriter提前关闭:代码开头创建writer后立刻执行writer.close(),后续循环中再调用该writer时已处于关闭状态,完全无法写入数据。
  • 无效的DataFrame合并:df_combined = pd.concat([df])只是对单个DataFrame做无意义的包装,没有实现多文件数据的累积合并。
  • 空文件读取报错:首次循环时output.xls是刚创建的空文件,pd.read_excel()会直接抛出解析错误,导致程序中断。
  • 冗余操作:df.to_csv(i.split(".")[0]+".csv")会覆盖原CSV文件,这并非需求中的必要步骤,属于无效操作。

修复后的代码(一次性合并写入)

这种方式效率更高,适合批量处理后统一写入:

import pandas as pd
import glob

# 获取当前目录下所有CSV文件
files = glob.glob("*.csv") 

# 初始化列表存储所有处理后的数据集
processed_dfs = []

for file in files:
    # 仅读取指定列
    df = pd.read_csv(file, usecols=['column1', 'column2'])
    # 添加文件名列(去除后缀)
    df['Filename Column'] = file.split(".")[0]
    # 打印验证数据
    print(df)
    # 将处理后的数据集加入列表
    processed_dfs.append(df)

# 合并所有数据集
combined_df = pd.concat(processed_dfs, ignore_index=True)

# 写入Excel文件(用with语句自动管理文件资源)
with pd.ExcelWriter('output.xls', engine='xlsxwriter') as writer:
    combined_df.to_excel(writer, index=False)

支持追加到已有Excel的版本

如果需要在已存在的Excel文件末尾追加数据,可使用以下代码:

import pandas as pd
import glob
import os

files = glob.glob("*.csv") 
processed_dfs = []

for file in files:
    df = pd.read_csv(file, usecols=['column1', 'column2'])
    df['Filename Column'] = file.split(".")[0]
    print(df)
    processed_dfs.append(df)

new_df = pd.concat(processed_dfs, ignore_index=True)
output_path = 'output.xls'

# 检查文件是否存在,实现追加逻辑
if os.path.exists(output_path):
    existing_df = pd.read_excel(output_path)
    final_df = pd.concat([existing_df, new_df], ignore_index=True)
else:
    final_df = new_df

# 写入最终数据
with pd.ExcelWriter(output_path, engine='xlsxwriter') as writer:
    final_df.to_excel(writer, index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:42:06