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

Python使用csv.DictWriter无需枚举循环删除CSV行的方法问询

Python CSV固定行数保留+追加操作优化方案

核心原理

CSV是纯文本线性存储格式,本身不支持随机位置的行删除/插入,所有修改操作本质都需要重写全量文件。我们可以将原实现的3次IO操作(追加写、读文件、全量写)合并为2次IO(读文件、全量写),彻底消除冗余读写。

优化后代码

import csv
from os.path import exists

stime = get_time_str()
new_dict = {'Time': stime, 'Queries': Querycounter.value}
Querycounter.value = 0
field_names = ['Time', 'Queries']
max_rows = 2880  # 含表头的最大文件行数,若要保留2880条数据可改为2881

csv_path = AlpacaQueriesCSVfile
all_rows = []

# 读取已有文件内容
if exists(csv_path):
    with open(csv_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        # 先存表头,再存所有数据行
        all_rows = [reader.fieldnames] + list(reader)

# 追加新行
all_rows.append(new_dict)

# 超过最大行数时截断,保留表头+最新的(max_rows-1)条数据
if len(all_rows) > max_rows:
    # 保留第0行(表头),删除前面多余的旧数据,只留后面的(max_rows-1)条
    all_rows = [all_rows[0]] + all_rows[-(max_rows-1):]

# 一次性写回文件
with open(csv_path, 'w', encoding='utf-8', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=field_names)
    writer.writeheader()
    # 写入所有数据行(跳过all_rows里的表头,用DictWriter自带的写头方法避免格式问题)
    writer.writerows(all_rows[1:])

优化说明

  • 全程只做1次读、1次写,消除原有实现的冗余IO操作
  • 统一使用DictReader/DictWriter处理字典格式数据,和原有业务逻辑对齐,无需额外格式转换
  • 兼容新文件初始化场景,自动写入表头,避免首次运行无表头的问题
  • 移除了with块中冗余的手动close()调用,上下文管理器会自动释放文件句柄
  • 修复了原代码中AlpacaQueriesCSVfile和QueriesCSVfile变量名不一致的笔误
  • 2880行数据总大小仅几十KB,全量读取到内存无任何性能压力,无需引入复杂的流式处理逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 01:54:08