将api结果写入csv

时间:2017-08-14 14:03:44

标签: python api csv

我有问题将我的api调用写入一个csv文件。我是关于Python的新手,看起来像是堆栈溢出,但无法弄明白。任何人都知道如何做到这一点?

这是电话的答案 http://i.imgur.com/xqPwtBH.jpg

这是我想要的方式 http://i.imgur.com/3pPzIs6.jpg

非常感谢,

这是代码

import datetime

from facebookads.adobjects.adaccount import AdAccount
from facebookads.adobjects.adsinsights import AdsInsights
from facebookads.api import FacebookAdsApi

start_date = datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
end_date = datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")


access_token = 'xxx'
ad_account_id = 'act_xx'
##app_secret = 'xxx'
FacebookAdsApi.init(access_token=access_token)

fields = [

'campaign_name',
'impressions',
'clicks',
'social_impressions',
'total_actions',

]
params = {
'time_range': {'since':start_date,'until':end_date},
##  'filtering': [],
'level': 'campaign',
##'breakdowns': ['days_1'],

}

print (AdAccount(ad_account_id).get_insights(
fields=fields,
params=params,
 ))

在尝试N. Ivanov的解决方案时,我仍然收到错误:

f = csv.writer(open'testfbhh.csv', 'wb+'

1 个答案:

答案 0 :(得分:0)

在伊万诺夫的帮助下,我找到了一个工作正常的解决方案。

我只是想知道是否有办法优化它,因为我觉得它可能更好。

感谢,

print (result,file = open ('export.json', 'w'))
with open('export.json', 'r') as file :
filedata = file.read()

# Replace the target which don't allow to convert my json into csv
filedata = filedata.replace('<AdsInsights> ', '')

# Write the file out again
with open('export.json', 'w') as file:
file.write(filedata)

with open('export.json') as json_data:
x = json.load(json_data)

f = csv.writer(open("test.csv", "w", newline=''))

# Write CSV Header, If you dont need that, remove this line


for x in x:
f.writerow([x["date_start"],
            x["date_stop"],
            x["impressions"],
            x["social_impressions"],
            x["total_actions"]])