Reputation: 31
I have 2 csv files and want to copy the column from score.csv to marklist.csv as 3rd column. Every 1 hrs score.csv file will get update and those column should be added as new column(4th column, 5th column) in marklist.csv
Python version - 2.7
marklist.csv
name,subject
angel,maths
mark,science
krish,social
score.csv
score
70
80
85
I have tried with below code but it was replacing the existing marklist.csv content itself.Please guide how to do this.
import csv
with open('score.csv', 'r') as readFile:
reader = csv.reader(readFile)
lines = list(reader)
with open('marklist.csv', 'w') as writeFile:
writer = csv.writer(writeFile)
writer.writerows(lines)
readFile.close()
writeFile.close()
Actual ouptut
marklist.csv
score
70
80
85
Expected output
marklist.csv
name,subject,score
angel,maths,70
mark,science,80
krish,social,85
Upvotes: 2
Views: 487
Reputation: 2943
You can do it like this
import csv
with open('score.csv', 'r') as score, open('marklist.csv', 'r') as marklist, \
open('result.csv', 'w') as result:
score_reader = csv.reader(score)
marklist_reader = csv.reader(marklist)
result = csv.writer(result)
result.writerows(x + y for x, y in zip(marklist_reader, score_reader))
Upvotes: 1