csv.DictWriter - 类型错误:__init __()至少需要3个参数(假设4) [英] csv.DictWriter -- TypeError: __init__() takes at least 3 arguments (4 given)
问题描述
我试着写字典的CSV列表时遇到问题初始化 csv.DictWriter()
。我有:
I'm trying to write a list of dictionaries to a CSV and am having issues initializing csv.DictWriter()
. I've got:
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)
我得到的错误是:
The error I get is:
TypeError: __init__() takes at least 3 arguments (4 given)
我试过的参数各种排列,但似乎并没有能够得到它运行。我也似乎没有能够找到任何人谁是有问题的。我没有尝试过指定的唯一参数是 * ARGS
和 ** kwds
。我是一个小白依然,尽管读书,我不明白他们在这种情况下如何工作的。任何想法?
I've tried various permutations of arguments, but don't seem to be able to get it to run. I also don't seem to be able to find anyone else who's had the problem. The only arguments I haven't tried specifying are *args
and **kwds
. I'm a noob still and despite reading, I don't understand how they work in this situation. Any ideas?
编辑:在最后的为
循环我有 writer.writerows()
里面也没有输出的全部类型的字典在列表中。更改为 writer.writerow()
。
in the final for
loop I had writer.writerows()
which did not output the all the dicts in the list. Changed to writer.writerow()
.
推荐答案
该参数的名称是字段名
(全部小写),而不是字段名
:
The name of the parameter is fieldnames
(all lowercase), not 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没有一个错误,如抱怨:
Note that Python doesn't complain with an error such as:
类型错误:DictWriter得到了一个意外的关键字参数的字段名
由于 csv.DictWriter
恰好有一个 ** kwds
参数。你可以看到它在文档如果你看一下签名
because csv.DictWriter
happens to have a **kwds
parameter. You can see it in the documentation if you look at the signature:
类csv.DictWriter(csvfile,字段名,restval ='',extrasaction ='加薪',方言='Excel的',* ARGS,** kwds)
这个参数将接受任意数量的关键字参数。
This parameter will accept any number of keyword arguments.
这篇关于csv.DictWriter - 类型错误:__init __()至少需要3个参数(假设4)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!