比较2个CSV文件之间的值并写入第3个CSV文件 [英] Comparing values between 2 CSV files and writing to a 3rd CSV file

查看:98
本文介绍了比较2个CSV文件之间的值并写入第3个CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较2个csv之间的特定列的值.我尝试了以下代码相同.但是,我没有得到任何输出,也没有错误.请帮助我

I am trying to compare values of a particular column between 2 csv. I tried the following code for the same. However, I am not getting any output and no error too. Please help me with this

with open("File1.csv", "rb") as in_file1, open("File2.csv", "rb") as in_file2,open("File3.csv", "wb") as out_file:
   reader1 = csv.reader(in_file1)
   reader2 = csv.reader(in_file2)
   writer = csv.writer(out_file)
   for row2 in reader2:
       for row1 in reader1:
           if row2[0] == row1[0]:
               row2[1] = row1[1]
       writer.writerow(row2)

这是数据的样子:

File 1

A 100
B 200
C 300
D 400
E 500

FIle 2

A
C
E
E
E
D

File 3 (Should be)

A 100
C 300
E 500
E 500
E 500
D 400

推荐答案

File1.csv是映射.首先阅读并将其存储在词典中.然后遍历File2.csv并将其与从映射字典中检索到的值一起写入File3.csv.

File1.csv is a mapping. Read it first and store it in a dictionary. Then iterate over File2.csv and write it to File3.csv together with the value retrieved from the mapping dictionary.

以下代码适用于您的示例:

The following code works for your example:

with open("File1.csv", "rb") as in_file1:
    d = dict(csv.reader(in_file1, delimiter=' '))

with open("File2.csv", "rb") as in_file2, open("File3.csv", "wb") as out_file:
    writer = csv.writer(out_file, delimiter=' ')
    for rec in csv.reader(in_file2, delimiter=' '):
        writer.writerow((rec[0], d[rec[0]]))

仅作说明,d看起来像这样:

Just for an illustration, d looks like this:

{'A': '100', 'B': '200', 'C': '300', 'D': '400', 'E': '500'}

这些值是字符串(不是整数),但这不是问题,因为我们只是将它们打印到文件中.

The values are strings (not integers), but this is not a problem, since we are just printing them into a file.

这篇关于比较2个CSV文件之间的值并写入第3个CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆