0
def csv_report(rec_id,msg1):
    with open('mycsv.csv', 'a',newline='') as f:
        thewriter = csv.writer(f)
        thewriter.writerow({rec_id,msg1})

我使用此函数在具有两个字段的 csv 文件中写入数据,但我得到的输出类似于 rec_id iam 获取 msg1 而代替 msg1 iam 获取 rec_id。附加输出。 在此处输入图像描述

4

1 回答 1

0

这个对我有用。它可能是提供该csv_report()功能的代码。下面是一个通用函数,可用于从字典数据附加/创建任何 csv:

import csv


def append_csv_dict(path, data):
    '''
    Append a csv with a dictionary keys as column headers

    Args:
        path (str): Path to the csv file
        data (dict): Dictionary with keys as column headers
                     and values as column data
    '''
    with open(path, 'a') as file:
        # set the field names to the keys of the dictionary
        fieldnames = list(data.keys())
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        # write the header if the file is new
        if file.tell() == 0:
            writer.writeheader()
        # write the row
        writer.writerow(data)

# write some of the names to the file
append_csv_dict('mycsv.csv', {'email': 'michael.lawson@reqres.in', 'message': 'Editor role has been enabled'})
append_csv_dict('mycsv.csv', {'email': 'lidsay.ferguson@reqres.in', 'message': 'Person already has editor access'})
append_csv_dict('mycsv.csv', {'email': 'tobias.funke@reqres.in', 'message': 'Editor role has been enabled'})
append_csv_dict('mycsv.csv', {'email': 'byron.fields@reqres.in', 'message': 'Person Account Created and ...'})
append_csv_dict('mycsv.csv', {'email': 'george.edwards@reqres.in', 'message': 'Person Account Created and ...'})
append_csv_dict('mycsv.csv', {'email': 'rachel.howell@reqres.in', 'message': 'Person Account Created and ...'})

输出:

email,message
michael.lawson@reqres.in,Editor role has been enabled
lidsay.ferguson@reqres.in,Person already has editor access
tobias.funke@reqres.in,Editor role has been enabled
byron.fields@reqres.in,Person Account Created and ...
george.edwards@reqres.in,Person Account Created and ...
rachel.howell@reqres.in,Person Account Created and ...
于 2020-05-05T17:02:06.123 回答