Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: argument 1 must have a "write" method

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
like image 569
user4943236 Avatar asked Oct 21 '16 06:10

user4943236


1 Answers

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.

like image 55
Martijn Pieters Avatar answered Oct 16 '22 04:10

Martijn Pieters