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

如何用Python创建CSV文件时添加固定值首列?

解决方案

直接修改build_csv函数中写入行的逻辑,将固定值PINCARD插入到每一行的开头即可:

def build_csv(filename, row_source):
  with open(filename, "w", newline="", encoding="utf-8") as csv_file:
    fixed = 'PINCARD'
    writer = csv.writer(csv_file, delimiter=";")
    for row in row_source:
        # 将固定值作为新的第一列,拼接到原行数据前
        writer.writerow([fixed] + list(row))

补充说明:

  • [fixed] + list(row):把固定值包装成单元素列表,再和转换为列表的原行数据拼接,生成包含固定列的新行
  • 如果你的row_source返回的row本身就是列表类型,list(row)可以省略,直接写[fixed] + row
  • 如果row是元组类型,list(row)会把它转成列表,确保拼接操作可行

如果你的查询结果包含表头,需要同时给表头也添加固定列的话,可以这样调整:

def build_csv(filename, row_source):
  with open(filename, "w", newline="", encoding="utf-8") as csv_file:
    fixed = 'PINCARD'
    writer = csv.writer(csv_file, delimiter=";")
    # 处理表头行
    first_row = next(row_source)
    writer.writerow([fixed] + list(first_row))
    # 处理剩余数据行
    for row in row_source:
        writer.writerow([fixed] + list(row))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:45:35