如何通过python将一列从csv添加到另一列csv

时间:2019-02-21 09:04:09

标签: python-2.7 csv

我有2个csv文件,并希望将该列从score.csv复制到marklist.csv作为第三列。每1小时score.csv文件将得到更新,这些列应作为新列(第四列,第五列)添加到marklist.csv

Python版本-2.7

marklist.csv

name,subject
angel,maths
mark,science
krish,social

score.csv

score
70
80
85

我尝试使用下面的代码,但是它正在替换现有的marklist.csv内容本身。请指导如何执行此操作。

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()

实际输出

marklist.csv
score
70
80
85

预期产量

marklist.csv
name,subject,score
angel,maths,70
mark,science,80
krish,social,85

1 个答案:

答案 0 :(得分:1)

您可以这样做

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))