My problem at hand is to get the data from API's and input that data into csv. I'm able to get the data, however outputting the data into csv is where I'm getting the error. Can someone please help.
Here is the sample code:
import csv,sys
def read_campaign_info(campaigns):
myfile = csv.writer(open("output.csv", "w"))
for insight in reach_insights:
account_id = str(insight[AdsInsights.Field.account_id])
objective = str(insight[AdsInsights.Field.objective])
metrics =[account_id,objective]
wr = csv.writer(myfile,quoting=csv.QUOTE_ALL)
wr.writerows(metrics)
Type of variable metrics
is <class 'list'>
Error that I'm getting is
wr = csv.writer(myfile,quoting=csv.QUOTE_ALL)
TypeError: argument 1 must have a "write" method
You are passing a csv.writer()
object to csv.writer()
:
myfile = csv.writer(open("output.csv", "w"))
wr = csv.writer(myfile,quoting=csv.QUOTE_ALL)
myfile
is a csv.writer()
object already. Pass your rows to that instead, or remove the csv.writer()
call from the myfile
line (but then move the wr = csv.writer(..)
line out of the loop, you only need to create this once).
I strongly recommend you use the file object as a context manager so it is closed properly. Also, you want to leave newline handling to the CSV module, so use newline=''
when opening the file:
with open("output.csv", "w", newline='') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
for insight in reach_insights:
account_id = insight[AdsInsights.Field.account_id]
objective = insight[AdsInsights.Field.objective]
wr.writerow([account_id, objective])
The csv.writer()
object handles conversions to string for you, so the str()
calls are redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With