Reputation: 73
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)
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?
Edit: in the final for
loop I had writer.writerows()
which did not output the all the dicts in the list. Changed to writer.writerow()
.
Upvotes: 1
Views: 4835
Reputation:
The name of the parameter is fieldnames
(all lowercase), not fieldNames
:
writer = csv.DictWriter(f, fieldnames=fieldNames, restval="", dialect="excel",)
Demo:
>>> 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>
>>>
Note that Python doesn't complain with an error such as:
TypeError: DictWriter got an unexpected keyword argument 'fieldNames'
because csv.DictWriter
happens to have a **kwds
parameter. You can see it in the documentation if you look at the signature:
class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds)
This parameter will accept any number of keyword arguments.
Upvotes: 3