使用 CSV writer 写入新字段

Write new field with CSV writer

我正在尝试根据 ID 号(如果 ID 号)在 CSV A 上写一个新行。例如在 CSV B 上看到,如果 ID = 1,则学生是女性,ID = 2 是男性。

CSV A(有 3 列)

ID, Age, FirstName
1,   18,   Lia
2,   18,   Joe
2,   18,   John

CSV B(有 2 列)

ID, Gender
1,    Female
2,    Male

根据此信息,所需的输出如下:

ID, Age, FirstName, Gender
1,   18,   Lia,     Female
2,   18,   Joe,     Male
2,   18,   John,    Male

如何使用 Python csv 编写器实现此目的?

我不完全明白你在这里的意思 但是我知道它会像这样

首先创建一个新的csv writer对象 然后写逻辑代码 将值附加到列表或元组 说的 wobj.writerow(列表名称)

我希望你做得很好,这个逻辑是基本的,但正如你上面提到的,你是 python 的新手,所以我做了一些代码供你参考,附在下面

    import csv
    newColumn = ''
    genderDict = {}
    with open('CSVB.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0

        for row in csv_reader: 
            if line_count == 0:
                newColumn = row[1]
                line_count = line_count+1
            else:
                genderDict[row[0]] = row[1]

    with open('CSVA.csv') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count == 0:
                with open('OUTPUT.csv', mode='w') as employee_file:
                    output_writer = csv.writer(employee_file, delimiter=',',  quotechar='"', quoting=csv.QUOTE_MINIMAL)
                    row.append(newColumn)
                    output_writer.writerow(row)
                line_count += 1
            else:
                with open('OUTPUT.csv', mode='a') as employee_file:
                    output_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                    row.append(genderDict[row[0]])
                    output_writer.writerow(row)
                line_count += 1