python - 比较两个 CSV 文件之间的值并写入第三个 CSV 文件

标签 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

最佳答案

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

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

关于python - 比较两个 CSV 文件之间的值并写入第三个 CSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14379921/

相关文章:

python - 使用 OpenCV 和 Python 将拼图图像拼接在一起

python - 为什么Numpy的RGB图像阵列具有4层而不是3层?

python - Django : Case insensitive matching of username from auth user?

python - 在 vim 中使用 UltiSnips 自定义自动完成

python - 返回字典中的最大值

python - 使用带有大 csv 的 pandas 结构(迭代和 block 大小)

linux - 如何在 CSV 中获取一行的散列并将其添加为最后一列

通过链接读取文件

python - 使用 Python 将具有参数限制的积分函数拟合到数据(德拜模型)

python-2.7 - Selenium python : what is 'lambda' in webdriverwait. 直到语句