Python:TypeError:参数1必须有"写"方法

时间:2016-10-21 06:59:51

标签: python python-3.x csv

我手头的问题是从API获取数据并将数据输入csv。我能够获取数据,但是将数据输出到csv是我收到错误的地方。有人可以帮忙。

以下是示例代码:

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)

变量metrics的类型为<class 'list'>

我得到的错误是

wr = csv.writer(myfile,quoting=csv.QUOTE_ALL)
TypeError: argument 1 must have a "write" method

1 个答案:

答案 0 :(得分:4)

您正在将csv.writer()对象传递给csv.writer()

myfile = csv.writer(open("output.csv", "w")) 
wr = csv.writer(myfile,quoting=csv.QUOTE_ALL)

myfilecsv.writer()对象已经。将您的行传递给它,或者从csv.writer()行中移除myfile调用(但随后将wr = csv.writer(..)行移出循环,您只需创建一次)。< / p>

我强烈建议您将文件对象用作上下文管理器,以便正确关闭。此外,您希望将换行处理留给CSV模块,因此在打开文件时请使用newline=''

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

csv.writer()对象为您处理转换为字符串,因此str()调用是多余的。