2015-09-26 47 views
0

我想使用Python的csv包操纵csv文件。我想打开csv文件,对其进行操作(将其从某些工件中清除),将更改写入另一个文件,完成。Python csv.DictWriter writerow()返回错误

我在写作部分有麻烦。我不确定我是否正确使用csv.DictWriter。我的代码的最后一行产生错误:

TypeError: init() takes at least 3 arguments (2 given)

为什么我得到这个错误?

import csv 


dataSource = 'dentistData.csv' 
dataTarget = 'test.csv' 

with open(dataSource) as source, open(dataTarget) as target: 

    reader = csv.DictReader(source, delimiter=",", quotechar='"') 
    writer = csv.DictWriter(target, delimiter=',') 

    for row in reader: 

     #if dentist_type is empty, add the type PRV (private dentist) 
     if not row['dentist_type']: 
      row['dentist_type']='PRV' 
     print(row['dentist_type']) 

     #remove lgh from street field 
     writer.writerow(row) 

回答

2

您缺少[csv.DictWriter](https://docs.python.org/2/library/csv.html#csv.DictWriter)的必需参数fieldnames

The fieldnames parameter is a sequence of keys that identify the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Note that unlike the DictReader class, the fieldnames parameter of the DictWriter is not optional. Since Python’s dict objects are not ordered, there is not enough information available to deduce the order in which the row should be written to the csvfile.

完整的签名是:从DOC

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

例子:

import csv 

with open('names.csv', 'w') as csvfile: 
    fieldnames = ['first_name', 'last_name'] 
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames) 

    writer.writeheader() 
    writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'}) 
    writer.writerow({'first_name': 'Lovely', 'last_name': 'Spam'}) 
    writer.writerow({'first_name': 'Wonderful', 'last_name': 'Spam'}) 
+0

谢谢!这解决了它。我错过了它说的部分*不是可选的*。 – seb