繁体   English   中英

如何将 Python 输出结果保存在 csv 中

[英]How to save Python output result in csv

我有下面的代码,我使用 Python 连接到 JIRA rest api,它工作正常。 现在我想将此响应保存到 csv 文件中,但不知道该怎么做。 我是 Python 代码的新手。

import requests
import json
import base64

# Base encode email and api token
cred =  "Basic " + base64.b64encode(b'XXXX:XXXX').decode("utf-8")
# Set header parameters
headers = {
   "Accept": "application/json",
   "Content-Type": "application/json",
   "Authorization" : cred
}

# Enter your project key here
projectKey = "TRT"

# Update your site url
url = "https://jira-test./rest/api/latest/search?jql=project%20%3D%20" + projectKey

# Send request and get response
response = requests.request(
   "GET",
   url,
   headers=headers
)

# Decode Json string to Python
json_data = json.loads(response.text)

# Display issues
for item in json_data["issues"]:
    print(item["id"] + "\t" + item["key"] + "\t" +
        item["fields"]["issuetype"]["name"] + "\t" +
        item["fields"]["created"]+ "\t" +
        item["fields"]["creator"]["displayName"] + "\t" +
        item["fields"]["status"]["name"] + "\t" +
        item["fields"]["summary"] + "\t"
        )

下面是输出的样子:

330479  OO-27  Ad-hoc  2021-10-14T09:29:41.000+0200   TST Backlog Testing the Report
330480  OO-28  Ad-hoc  2021-10-14T09:29:41.000+0200   TST Backlog Testing the Report
330481  OO-29  Ad-hoc  2021-10-14T09:29:41.000+0200   TST Backlog Testing the Report

您可以尝试将 dict/json 转换为 Pandas DataFrame,然后使用DataFrame.to_csv()

import pandas as pd

df = pd.DataFrame.from_dict(dict_var)

df.to_csv("name_of_your_file.csv")

它保存到运行 python 代码的任何文件夹。

或者,如果 dict 还不是所需的格式,您可以手动创建一个 csv 文件并附加到它:

with open("file.csv", "a") as file_to_append_to:
    file_to_append_to.write("...") #first line is the columns, such as "id,name,address,whatever"
    for item in json_file:
        item_line = f'{item["id"]},{item["key"]},{item["fields"]["issuetype"]["name"]}...'
        file_to_append_to.write(item_line)
import pandas as pd
issues = json_data["issues"]
data = {"id": [item["id"] for item in issues], 
        "key": [item["key"] for item in issues],
....
}
df = pd.DataFrame(data=data)
df.to_csv("tabseparated.csv", sep="\t")

看看convtools库,它是轻量级的,它包含了很多数据处理原语。

from convtools import conversion as c
from convtools.contrib.tables import Table

# please, provide the input data next time :)
input_data = {
    "issues": [
        {
            "id": 330479,
            "key": "OO-27",
            "fields": {
                "issuetype": {
                    "name": "Ad-hoc",
                },
                "created": "2021-10-14T09:29:41.000+0200",
                "creator": {"displayName": "TST"},
                "status": {"name": "Backlog"},
                "summary": "Testing the Report",
            },
        },
    ]
}

# define the schema
schema = {
    "id": c.item("id"),
    "key": c.item("key"),
    "name": c.item("fields", "issuetype", "name"),
    "created": c.item("fields", "created"),
    "creator": c.item("fields", "creator", "displayName"),
    "status": c.item("fields", "status", "name"),
    "summary": c.item("fields", "summary"),
}

# here we process every issue, results in iterable of tuples
converter = c.item("issues").iter(tuple(schema.values())).gen_converter()

# using schema keys as column names and processed rows as data
Table.from_rows(converter(input_data), header=list(schema)).into_csv(
    "output.csv", dialect=Table.csv_dialect(delimiter="\t")
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM