2017-08-14 131 views
-1

我的问题是将我的api调用写入一个csv文件。我是Python新手,看起来很周到,但无法弄清楚。任何人有一个想法如何做到这一点?将api结果写入csv

这里就是答案加时赛通话 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.伊万诺夫时,我仍然得到一个错误:

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

的可能重复[我怎样才能转换JSON到CSV?](https://stackoverflow.com/questions/1871524/how-can-i-convert-json-to- CSV) –

+0

N.伊万诺夫,我想这个解决办法,但我得到一个错误,无效的语法为:F = csv.writer(open'test.csv”,‘WB +’) – sof

+0

以及你显然有一个错误有.. 。我建议你先做一些python教程。否则,你会在'open'调用周围丢失'()'。 –

回答

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"]])