如何在CSV文件中插入数据?

发布于 2025-02-11 18:05:34 字数 1112 浏览 0 评论 0原文

我的python脚本有问题。

基本上,我的脚本首先是对我们的API进行get请求,并从端点提取所有ID,然后将其保存在CSV文件中。

ATM IM在CSV文件中插入数据时遇到问题。 之后,我想要的是我的CSV文件看起来像这样

id
1
2
3
...

在将数据插入到:基本上我想要自己的行中的每个ID

。但是最终被插入的是:

id
1,2,3,...

我尝试过循环和其他几件事,而似乎没有任何作用。如果有人能帮助我解决这个问题,我会很乐意。我只是错过了这一点。

我的脚本代码:

import requests
import json
import csv
from jsonpath_ng import jsonpath, parse

url = 'url'

headers = {
       "Authorization": "Bearer token"
    }

response = requests.get(url_v1, headers=headers)

JsonResponse = response.json()
converted = json.dumps(JsonResponse)

Data = json.loads(converted)
ParseData = parse('$..id')
Id = ParseData.find(Data)


open_file = open('C:/File/test.csv','w', newline='')
writer = csv.writer(open_file)

list_id = []
fields = ['id']

for i in range(0, len(Id)):
    result = Id[i].value
    list_id.append(result)

writer.writerow(fields)

writer.writerow(list_id)


open_file.close()

I have a problem with my Python script.

Basically what my script does is first it does a GET request to our API and extracts all ID's from the endpoint and then saves it in a CSV file.

Atm im having problems inserting data in the csv file. What i want is for my csv file to look like this after inserting data in:

id
1
2
3
...

Basically I want every id in their own row.

But what ends up being inserted is this:

id
1,2,3,...

I have tried for looping and few other things and nothing seemed to work out. I would love if anyone can help me with this problem. It's probably something really simple I just missed out.

My script code:

import requests
import json
import csv
from jsonpath_ng import jsonpath, parse

url = 'url'

headers = {
       "Authorization": "Bearer token"
    }

response = requests.get(url_v1, headers=headers)

JsonResponse = response.json()
converted = json.dumps(JsonResponse)

Data = json.loads(converted)
ParseData = parse('$..id')
Id = ParseData.find(Data)


open_file = open('C:/File/test.csv','w', newline='')
writer = csv.writer(open_file)

list_id = []
fields = ['id']

for i in range(0, len(Id)):
    result = Id[i].value
    list_id.append(result)

writer.writerow(fields)

writer.writerow(list_id)


open_file.close()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文