将字典作为参数传递给python中的csv写函数

时间:2019-02-22 05:20:29

标签: python-3.x csv dictionary

我想一次将数据附加到csv文件的多列中。

我已经为其定义了一个函数“ writeCSV”,该函数将col_name和col_value附加到csv文件中。

def writeCSV(col_name,col_data):

    with open('COMPONENT_DETAILS.csv',"a") as COMPONENT_DETAILS_file:

        fieldnames = ['ID','module_name','module_id','tech_name','component_name','connecion','counter','connection_type']
        csv_writer = csv.DictWriter(COMPONENT_DETAILS_file,fieldnames=fieldnames)
        csv_writer.writerow({col_name:col_data})

现在,假设我想将数据追加到tech_name,component_name,connection_type列中,如何将参数传递给writeCSV()函数?字典在这里有用吗?

现在,我只能通过使用以下语法调用函数来将内容仅追加到一列

writeCSV('tech_name': 'Python')

1 个答案:

答案 0 :(得分:1)

def writeCSV(dictionary):
        ##Your code
        csv_writer.writerow(dictionary)

writeCSV({'tech_name': 'Python2','component_name': 'Python3'})

这应该可以完成您的工作。由于已经定义了用于写入csv的 DictWriter ,因此实现此方法将没有问题。