3

我正在尝试比较 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
4

2 回答 2

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'}

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

于 2013-01-17T13:17:12.103 回答
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 的意义

于 2013-01-17T13:25:50.580 回答