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

Python Tkinter下向CSV文件指定列逐行追加数据的实现方法问询

问题核心原因

你当前使用的w+文件打开模式为覆盖写入模式,每次打开文件时会清空已有内容,无法实现追加效果。同时现有写法每次运行都会重复写入表头,不符合追加场景的使用逻辑。

修改方案

按照以下两个步骤调整即可实现需求:

  • 将文件打开模式替换为a+(追加读写模式),同时新增文件存在性判断,仅当文件首次创建、内容为空时写入表头,避免表头重复。
  • 保持行写入逻辑不变,writerow方法默认会在文件最后一行的下一行写入新内容,只要传入的列表元素顺序和表头列顺序对应,就会自动写入到对应列的位置。
完整修改后代码示例
import csv
import os

# 预先判断目标文件是否已存在
file_exists = os.path.isfile(filename)

# 用a+模式打开文件,newline参数避免Windows系统下生成多余空行
with open(filename, 'a+', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    # 仅首次创建文件时写入表头
    if not file_exists:
        writer.writerow(['Column1', 'Column2', 'Column3'])
    # 逐行追加数据
    for items in self.data_List:                
        print('items', items)
        # 列表元素顺序与表头顺序一一对应,即可写入对应列
        writer.writerow([items, self.displayData112, self.displayData])
可选优化:列名绑定写入

如果需要严格避免列顺序错乱导致的写错位问题,可以改用csv.DictWriter通过列名绑定写入数据,无需关注列表顺序:

import csv
import os

file_exists = os.path.isfile(filename)

with open(filename, 'a+', newline='', encoding='utf-8') as file:
    # 定义列名映射
    field_names = ['Column1', 'Column2', 'Column3']
    writer = csv.DictWriter(file, fieldnames=field_names)
    if not file_exists:
        writer.writeheader()
    for items in self.data_List:
        # 直接通过列名指定对应字段,不会出现列错位问题
        writer.writerow({
            'Column1': items,
            'Column2': self.displayData112,
            'Column3': self.displayData
        })
注意事项
  • 打开文件时建议显式指定encoding编码参数,避免不同操作系统之间切换时出现中文乱码问题。
  • 追加写入前尽量做好数据格式校验,避免写入不符合列规则的异常数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 02:39:03