本文介绍了用Python语言将API结果写入CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一些使用Python将API结果写入.CSV文件的帮助。此时,我成功地写入了.CSV,但我似乎无法确定我正在寻找的.CSV格式背后的代码,即标准的一字段=一列格式。
如有任何帮助,我们不胜感激!具体内容如下。谢谢!
我的代码:
import requests
import json
import csv
urlcomp = 'http://url_ommitted/api/reports/completion?status=COMPLETED&from=2016-06-01&to=2016-08-06'
headers = {'authorization': "Basic API Key Ommitted", 'accept': "application/json", 'accept': "text/csv"}
## API Call to retrieve report
rcomp = requests.get(urlcomp, headers=headers)
## API Results
data = rcomp.text
## Write API Results to CSV
with open('C:\_Python\testCompletionReport.csv', "wb") as csvFile:
writer = csv.writer(csvFile, delimiter=',')
for line in data:
writer.writerow(line)
上面的代码创建了一个具有正确输出的.CSV,但它将API结果中的每个字符写入输出文件A列中的一个新单元格。下面的屏幕截图:
我还尝试了下面的代码,它将整个API结果集写入.CSV输出文件中的单个单元格。
编码:
data = rcomp.text
with open('C:\_Python\CompletionReportOutput.csv', 'wb') as csvFile:
writer = csv.writer(csvFile, delimiter = ',')
writer.writerow([data])
输出:
下面是我的调用返回的一些示例API结果数据的屏幕截图:
我要在最终的.CSV输出文件中查找的示例:
编辑-API响应示例:
"包裹已创建","包裹ID","包裹名称","包裹状态","已废弃包裹","包裹已更新","发件人ID","发件人名称","发件人公司","发件人已创建","发件人电子邮件","发件人姓名","发件人语言","发件人姓氏","发件人电话","发件人标题","发件人已更新","发件人已激活","发件人锁定","发件人状态","发件人类型" "Tsinghua Aug 04 14:52:57 CDT 2016","ulw5MTQo8WjBfoCTKqz9LNCFpV4=","Tstone to TestTwo-Flat PDF Remote","Complete","FALSE","清华08-04 14:53:30 CDT 2016","tKpohv2kZ2oU","2016-08-03 14:12:06.904","TestAccount@est.com","John","en","Smith","2016-08-03 14:12:06.942118",",""空"、"空"、"邀请"、"常规" "清华08月04日09:39:22 CDT 2016","IJV3U_yjPlxS-TVQgMr NgVUSss=","Tstone to TestTwo-Email测试","已完成","FALSE","清华08-04 10:11:29 CDT 2016","tKpohv2kZ2oU","2016-08-03 14:12:06.904","TestAccount@Test.com","John","en","Smith","2016-08-03 14:12:06.942118","空","空","邀请","常规"第二次编辑-根据Lee的建议输出:
推荐答案
所以,我最终偶然发现了一个解决方案。不确定这是否是处理此问题的"正确"方法,但下面的代码将API结果直接写入具有正确列格式的.CSV。
# Get JSON Data
rcomp = requests.get(urlcomp, headers=headers)
# Write to .CSV
f = open('C:\_PythonTwo\newfile.csv', "w")
f.write(rcomp.text)
f.close()
这篇关于用Python语言将API结果写入CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!