比较2个CSV文件之间的值并写入第3个CSV文件

时间:2013-01-17 13:13:20

标签: python csv python-2.7

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

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

2 个答案:

答案 0 :(得分:2)

File1.csv是一个映射。首先阅读它并将其存储在字典中。然后迭代File2.csv并将其与从映射字典中检索的值一起写入File3.csv。

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

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看起来像这样:

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

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

答案 1 :(得分:1)

为什么不这样简单地使用它:

lookup = {}                                                                     
with open('file1', 'r') as f:                                                   
    lookup = dict([l.split() for l in f.read().split('\n') if len(l) > 0])         
with open('file2', 'r') as file2, open('out', 'w') as out:                      
    for line in file2.readlines():                                              
        line = line.strip()                                                     
        out.write("%s %s\n" % (line, lookup[line]))

我在这里没有看到使用csv的观点