Skip to content
Advertisement

Write new field with CSV writer

I am trying to write a new row on CSV A based on the ID number if the ID number. For example as seen on CSV B if ID = 1 then the student is a Female, ID = 2 is a Male.

CSV A (has 3 columns)

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

CSV B (has 2 columns)

ID, Gender
1,    Female
2,    Male

Based on this information the desired output is below:

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

How can I achieve this using the Python csv writer?

Advertisement

Answer

I hope you are doing good, well this logic is basic but as you mentioned above you are new to python so I have done some code for your reference which is attached below

    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
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement