Pythoncsv.DictWriterwriterow()返回

2024-06-07 07:23:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个csv文件来操作Python的文件。我想打开csv文件,操作它(从某些人工制品中清除它),将更改写入另一个文件,完成。在

我在写作方面有困难。我不确定我是否在使用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)

Tags: 文件csvsourcetargetastype错误open
1条回答
网友
1楼 · 发布于 2024-06-07 07:23:55

缺少[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.

完整的签名是:

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

文件示例:

^{pr2}$

相关问题 更多 >