csv.DictWriter - TypeError:__ init __()至少需要3个参数(给定4个)

时间:2015-01-09 04:13:03

标签: python csv arguments

我正在尝试将一个字典列表写入CSV,并且在初始化csv.DictWriter()时遇到问题。我有:

fname = "Machine Detection Rate.csv"
with open(fname, "wb") as f:
    fieldNames = ["Number of Packets", "Number of Machines"]
    writer = csv.DictWriter(f, fieldNames=fieldNames, restval="", dialect="excel",)
    writer.writeheader()
    for line in machineCounter:
        print "Got Here!"
        writer.writerow(line)

我得到的错误是:

TypeError: __init__() takes at least 3 arguments (4 given)

我尝试了各种各样的参数排列,但似乎无法让它运行起来。我似乎也找不到其他有问题的人。我未尝试指定的唯一参数是*args**kwds。我仍然是一个菜鸟,尽管阅读,但我不明白它们在这种情况下是如何工作的。有什么想法吗?

编辑:在最后的for循环中,我有writer.writerows(),但没有输出列表中的所有词组。已更改为writer.writerow()

1 个答案:

答案 0 :(得分:3)

参数的名称为fieldnames(全部小写),而不是fieldNames

writer = csv.DictWriter(f, fieldnames=fieldNames, restval="", dialect="excel",)

演示:

>>> import csv
>>>
>>> with open('test.csv') as f:
...     fieldnames = ["Number of Packets", "Number of Machines"]
...     writer = csv.DictWriter(f, fieldNames=fieldnames, restval="", dialect="excel",)
...
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: __init__() takes at least 3 arguments (4 given)
>>>
>>> with open('test.csv') as f:
...     fieldNames = ["Number of Packets", "Number of Machines"]
...     writer = csv.DictWriter(f, fieldnames=fieldNames, restval="", dialect="excel",)
...
>>> writer
<csv.DictWriter instance at 0x01AD8E90>
>>>

请注意,Python不会抱怨错误,例如:

TypeError: DictWriter got an unexpected keyword argument 'fieldNames'

因为csv.DictWriter恰好有**kwds参数。如果您查看签名,可以在documentation中看到它:

class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)

此参数将接受任意数量的关键字参数。