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

使用Python转换大CSV到Excel的内存及追加写入问题

解决大型CSV转XLSX时分块追加写入的问题

问题背景

将约100MB的大型CSV文件转换为XLSX格式时,直接读取整文件会出现内存不足问题;改用分块写入方案后,又出现每次写入都会覆盖已有文件内容的情况,需要实现分块向同一XLSX文件追加写入的方法。

当前代码的问题

当前代码每次循环都会重新创建new_file.xlsx,导致之前写入的内容被覆盖:

import pandas as pd

n = 1000  # 每块行数
df = pd.read_csv("myFile.csv")

for i in range(0, df.shape[0], n):
    df[i:i+n].to_excel(f"new_file.xlsx", index=False, header=False)

解决方案

使用openpyxl引擎的mode参数实现追加写入,同时控制仅在第一次写入时添加表头,后续分块跳过表头:

优化后代码

import pandas as pd

chunk_size = 1000  # 每块行数
csv_file = "myFile.csv"
xlsx_file = "new_file.xlsx"

# 获取CSV文件的表头
header = pd.read_csv(csv_file, nrows=0).columns

# 分块读取CSV并追加写入XLSX
for chunk_index, chunk in enumerate(pd.read_csv(csv_file, chunksize=chunk_size)):
    # 仅第一次写入时添加表头
    write_header = chunk_index == 0
    # 首次写入用'w'模式创建文件,后续用'a'模式追加
    write_mode = 'w' if chunk_index == 0 else 'a'
    
    chunk.to_excel(
        xlsx_file,
        index=False,
        header=write_header,
        mode=write_mode,
        engine='openpyxl'
    )

关键要点

  • 用pd.read_csv的chunksize参数分块读取CSV,避免一次性加载整文件占用过多内存
  • 依赖openpyxl引擎的mode='a'实现追加写入,首次写入用mode='w'初始化文件
  • 通过循环索引控制表头写入时机,避免重复写入表头

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:05:32