例如,考虑文件a.csv
1 23 'better' 0
2 21 'bad' 0
3 34 'good' 0
和b.csv
23 2
34 5
我们可以得到结果:
1 23 'better' 2
2 21 'bad' 0
3 34 'good' 5
答案 0 :(得分:2)
感谢您提出更清晰的问题。此代码不会在原位修改文件A,而是使用输出文件fileC。
import csv #imports module csv
filea = "fileA.csv"
fileb = "fileB.csv"
output = "fileC.csv"
delim = ";" #set your own delimiter
source1 = csv.reader(open(filea,"r"),delimiter=delim)
source2 = csv.reader(open(fileb,"r"),delimiter=delim)
#open csv readers
source2_dict = {}
# prepare changes from file B
for row in source2:
source2_dict[row[0]] = row[1]
# write new changed rows
with open(output, "w") as fout:
csvwriter = csv.writer(fout, delimiter=delim)
for row in source1:
# needs to check whether there are any changes prepared
if row[1] in source2_dict:
# change the item
row[3] = source2_dict[row[1]]
csvwriter.writerow(row)
我希望我理解你的意图。
只是对步骤的简短解释:
答案 1 :(得分:0)
阅读a.csv
a_content = [l.split() for l in open('a.csv')]
阅读b.csv
b_dict = {k:v for k,v in [l.split() for l in open('b.csv')]}
输出修改后的数据
for rec in a_content:
if rec[1] in b_dict:
rec[3] = b_dict[rec[1]]
outfile.write(" ".join(rec)+'\n')
附录
考虑一下,单个print
语句会做
print "\n".join(" ".join(i[:-1]+([b[i[1]]]if i[1]in b else[i[-1]]))for b in[{k:v for k,v in[l.split()for l in open('b.csv')]}]for i in[l.split()for l in open('a.csv')])