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

如何将Python代码执行结果存储到CSV文件 现有代码无法写入如何解决

代码修改方案

原代码核心问题

  • 存在无效冗余代码:data_csv= csv.reader(f, delimiter=',') 没有实际作用,且此时json文件已经读取完成、文件对象已关闭,这行代码可直接删除
  • 写入内容不符合预期:你调用output_data.writerow(d)时,变量d是遍历json数组时留下的最后一个测试用例字典,不是你要保存的统计结果,且字典直接传入writerow只会写入字典的key值,完全不符合需求
  • 缺少CSV格式规范:没有定义表头、也没有把需要存储的统计结果组装成符合CSV写入要求的列表结构

修改后可运行代码

import csv
import json
from collections import Counter

# 读取JSON数据
with open('simplejson2.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

# 统计测试结果
c_total = Counter(k[:] for d in data for k, v in d.items() if k.startswith('sta') and v)
total_case = c_total['status']
c_failed = Counter(k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed'))
failed_case = c_failed['status']

# 写入CSV文件,添加newline参数避免Windows下出现多余空行
with open('result.csv', 'w', newline='', encoding='utf-8') as output:
    output_data = csv.writer(output, delimiter=',')
    # 写入表头
    output_data.writerow(['总测试用例数', '失败用例数', '执行结果'])
    # 组装统计结果写入
    print("there are total", total_case, "test case")
    if failed_case > 0:
        res_desc = f"存在{failed_case}个失败用例"
        print("There are", failed_case, "failed cases")
    else:
        res_desc = "全部用例执行通过"
        print("there are", failed_case, "sucessfully pass")
    output_data.writerow([total_case, failed_case, res_desc])

生成的result.csv内容示例

总测试用例数,失败用例数,执行结果
3,2,存在2个失败用例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 14:42:04