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)
JavaScript
x
5
1
ID, Age, FirstName
2
1, 18, Lia
3
2, 18, Joe
4
2, 18, John
5
CSV B (has 2 columns)
JavaScript
1
4
1
ID, Gender
2
1, Female
3
2, Male
4
Based on this information the desired output is below:
JavaScript
1
5
1
ID, Age, FirstName, Gender
2
1, 18, Lia, Female
3
2, 18, Joe, Male
4
2, 18, John, Male
5
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
JavaScript
1
31
31
1
import csv
2
newColumn = ''
3
genderDict = {}
4
with open('CSVB.csv') as csv_file:
5
csv_reader = csv.reader(csv_file, delimiter=',')
6
line_count = 0
7
8
for row in csv_reader:
9
if line_count == 0:
10
newColumn = row[1]
11
line_count = line_count+1
12
else:
13
genderDict[row[0]] = row[1]
14
15
with open('CSVA.csv') as csv_file:
16
csv_reader = csv.reader(csv_file, delimiter=',')
17
line_count = 0
18
for row in csv_reader:
19
if line_count == 0:
20
with open('OUTPUT.csv', mode='w') as employee_file:
21
output_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
22
row.append(newColumn)
23
output_writer.writerow(row)
24
line_count += 1
25
else:
26
with open('OUTPUT.csv', mode='a') as employee_file:
27
output_writer = csv.writer(employee_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
28
row.append(genderDict[row[0]])
29
output_writer.writerow(row)
30
line_count += 1
31