简体   繁体   English

Python csv.DictWriter writerow()返回错误

[英]Python csv.DictWriter writerow() returns error

I'm trying to manipulate a csv file using Python's csv package. 我正在尝试使用Python的csv软件包来处理csv文件。 I want to open the csv file, manipulate it (clean it from certain artefacts), write the changes to another file, done. 我想打开csv文件,对其进行操作(将其从某些文物中清除),将更改写入另一个文件,完成。

I'm having troubles with the writing part. 我在写作方面遇到麻烦。 I'm not sure whether I'm using the csv.DictWriter correctly. 我不确定我是否正确使用csv.DictWriter。 The last line of my code produces the error: 我的代码的最后一行会产生错误:

TypeError: init () takes at least 3 arguments (2 given) TypeError: init ()至少接受3个参数(给定2个)

Why am I getting this error? 为什么会出现此错误?

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)

You are missing the mandatory parameter fieldnames of [csv.DictWriter](https://docs.python.org/2/library/csv.html#csv.DictWriter) . 您缺少[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. fieldnames参数是一个键序列,用于标识字典中传递给writerow()方法的值写入csvfile的顺序。

Note that unlike the DictReader class, the fieldnames parameter of the DictWriter is not optional. 请注意,与DictReader类不同,DictWriter的fieldnames参数不是可选的。 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. 由于Python的dict对象未排序,因此没有足够的信息来推断应将行写入csvfile的顺序。

The complete signature is: 完整的签名是:

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

Example from doc: 来自doc的示例:

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'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM