【问题标题】:Comparing values between 2 CSV files and writing to a 3rd CSV file比较 2 个 CSV 文件之间的值并写入第 3 个 CSV 文件
【发布时间】:2013-01-17 13:13:19
【问题描述】:

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

【问题讨论】:

    标签: python csv python-2.7


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

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

      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 的意义

      【讨论】:

        猜你喜欢
        • 2018-11-19
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 2014-06-08
        • 2019-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多