【问题标题】:how to store python code output to csv file如何将python代码输出存储到csv文件
【发布时间】:2021-09-25 04:07:27
【问题描述】:

我想将我的 python 代码结果存储到 csv 文件中,但这是我的 python 代码,我没有在我的 csv 文件中显示我的 python 结果

import csv
import json
from collections import Counter

with open('result.csv', 'w') as output:
    with open('simplejson2.json', 'r') as f:
        str1=f.read()

    output_data=csv.writer(output, delimiter=',')
    data_csv= csv.reader(f, delimiter=',')
    data=json.loads(str1)

    c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('sta') and v)
    output_data.writerow(d)
    print("there are total", c['status'], "test case")

    c = Counter(k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed'))
    output_data.writerow(d)

    if c['status'] > 0:
        print("There are", c['status'], "failed cases")
    else:
        print("there are", c['status'], "sucessfully pass")

这是我的 simplejson2.json 文件

[
  {
    "status": "passed",
    "name": "Whiskers",
    "species" : "cat",
    "foods": {
      "likes": ["celery", "strawberries"],
      "dislikes": ["carrots"]
    }
  },
  {
    "status": "failed",
    "name": "Woof",
    "species" : "dog",
    "foods": {
      "likes": ["dog food"],
      "dislikes": ["cat food"]
    }
  },
  {
    "status": "failed",
    "name": "Fluffy",
    "species" : "cat",
    "foods": {
      "likes": ["canned food"],
      "dislikes": ["dry food"]
    }
  }
]

我的python代码输出是:-

总共有 3 个测试用例 有 2 个测试用例失败

【问题讨论】:

  • 将其保存在 txt 文件中? @东京
  • 不,我想保存为 csv 文件格式
  • 实际问题是什么?
  • 您的代码似乎有缩进问题
  • 实际问题是我的 python 代码输出未存储在 csv 文件中,但生成了 csv 文件我希望在 csv 文件中显示我的 python 代码结果

标签: python csv export-to-csv


【解决方案1】:

您正在尝试将d 保存在未分配到任何地方的 csv 中。您仅在此处分配 d,这在此处之外不可用。或者您想将c 保存在csv 中,但您错误地写了d

根据评论编辑:

with open('simplejson2.json', 'r') as f:
        str1=f.read()
        data_csv= csv.reader(f, delimiter=',')

您只能在with 中读取f。如果您尝试在with 之外读取f,则该文件已关闭,您将给出该错误。

【讨论】:

  • 我的控制台显示这个:-data_csv= csv.reader(f, delimiter=',') TypeError: argument 1 must be an iterator
  • 这个问题是因为你已经关闭了那个文件。所以,你不能再读了。我已编辑答案尝试查看那里。
  • @tokyo 你的问题现在解决了吗?如果已解决,则将答案标记为已接受!
  • data_csv= csv.reader(f, delimiter=',') 很奇怪:此时f 已经用尽,因此与data_csv 一起工作将立即导致StopIteration。此外,op 的程序对它没有任何作用。
  • @Timus 我应该编辑什么?我没明白你的意思。
【解决方案2】:

不知道你想要达到什么目的(或者为什么你需要一个计数器而不是仅仅使用len),但这是你代码的一个工作版本:

import csv
import json
from collections import Counter

with open('result.csv', 'w') as output:
    with open('simplejson2.json', 'r') as f:
        str1=f.read()

        output_data=csv.writer(output, delimiter=',')
        data_csv= csv.reader(f, delimiter=',')
        data=json.loads(str1)

        status_fields = [k[:] for d in data for k, v in d.items() if k.startswith('sta') and v]
        c = Counter(status_fields)
        output_data.writerow(status_fields)
        print("there are total", c['status'], "test case")

        status_fields_failed = [k[:] for d in data for k, v in d.items() if k.startswith('status') and v.startswith('failed')]
        c = Counter(status_fields_failed)
        output_data.writerow(status_fields_failed)

        if c['status'] > 0:
            print("There are", c['status'], "failed cases")
        else:
            print("there are", c['status'], "sucessfully pass")

生成的文件内容result.csv

status,status,status
status,status

所做的更改:

  • 缩进
  • 固定 for 循环表达式(d 未定义,Counter 构造函数需要可迭代)

【讨论】:

  • data_csv = csv.reader(f, delimiter=',') 似乎没有必要。另外,你可以直接做data = json.load(f),不用str1-detour?
猜你喜欢
  • 2021-05-17
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-09
  • 1970-01-01
  • 2022-07-21
相关资源
最近更新 更多