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

如何将pandas DataFrame追加写入单个Excel/CSV文件替代每日生成新文件

解决方案

CSV存储方案(推荐,性能好、实现简单)

直接使用pandas自带的to_csv方法的追加模式,无需手动处理文件写入逻辑,可自动适配数据格式:

  1. 新增文件存在性判断,首次写入保留表头,后续追加自动跳过表头避免重复
  2. 完整代码示例:
import os
import pandas as pd
import time

# --- 你原有生成当日dataframe的逻辑保持不变 ---
dataframe_for_excel_file_structure = {'id': pd.Series(ids) ,'date': date_for_each_sheet, 'type_of_property': pd.Series(type_of_property), 'area': pd.Series(sqm_area), 'location': pd.Series(locations), 'price_per_m2': pd.Series(price_per_m2), 'total_price': pd.Series(prices), 'published_by': pd.Series(publisher), 'link': pd.Series(link_for_offer)}
dataframe_for_excel = pd.DataFrame(dataframe_for_excel_file_structure)
# --- 原有逻辑结束 ---

# 统一存储的目标文件名
target_csv = 'all_house_crawled_data.csv'
# 判断文件是否已存在
file_exists = os.path.exists(target_csv)

# 追加写入,index=False表示不存储pandas默认行索引,encoding用utf-8-sig避免中文乱码
dataframe_for_excel.to_csv(
    target_csv,
    mode='a',
    header=not file_exists,
    index=False,
    encoding='utf-8-sig'
)

你之前报错是因为原生write方法仅支持字符串输入,你传入了列表类型参数,用pandas自带方法会自动完成数据类型转换、格式对齐,无需手动处理每一行内容。

Excel存储方案

如果必须使用Excel格式存储,需要借助openpyxl库实现追加写入:

  1. 先安装依赖:pip install openpyxl
  2. 完整代码示例:
import os
import pandas as pd
import time
from openpyxl import load_workbook

# --- 你原有生成当日dataframe的逻辑保持不变 ---
dataframe_for_excel_file_structure = {'id': pd.Series(ids) ,'date': date_for_each_sheet, 'type_of_property': pd.Series(type_of_property), 'area': pd.Series(sqm_area), 'location': pd.Series(locations), 'price_per_m2': pd.Series(price_per_m2), 'total_price': pd.Series(prices), 'published_by': pd.Series(publisher), 'link': pd.Series(link_for_offer)}
dataframe_for_excel = pd.DataFrame(dataframe_for_excel_file_structure)
# --- 原有逻辑结束 ---

target_excel = 'all_house_crawled_data.xlsx'
file_exists = os.path.exists(target_excel)

if file_exists:
    # 读取已有Excel文件
    book = load_workbook(target_excel)
    writer = pd.ExcelWriter(target_excel, engine='openpyxl')
    writer.book = book
    # 同步已有工作表信息,避免覆盖原有数据
    writer.sheets = {ws.title: ws for ws in book.worksheets}
    # 从已有数据的下一行开始写入,不重复写表头
    dataframe_for_excel.to_excel(
        writer,
        startrow=writer.sheets['Sheet1'].max_row,
        header=False,
        index=False
    )
else:
    # 首次创建文件写入
    dataframe_for_excel.to_excel(target_excel, index=False)

writer.save()
writer.close()

可选优化

可以新增数据去重逻辑,避免同一条数据被重复写入:

# 写入前先读取已有数据的id列,过滤重复数据
if file_exists:
    # CSV方案去重示例
    existed_df = pd.read_csv(target_csv, usecols=['id'])
    dataframe_for_excel = dataframe_for_excel[~dataframe_for_excel['id'].isin(existed_df['id'])]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:54:03