比较两个CSV文件并打印不同的Python行 [英] Compare two CSV files and print the rows that are different Python

查看:1026
本文介绍了比较两个CSV文件并打印不同的Python行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图比较下面的两个csv文件

I'm trying to compare two csv files that are like below

English.csv
i
am
is
was
were

Dictionary.csv
i,insomnia
d,disease
bc,breast cancer

我试图比较两个文件中的第一列,并打印与Dictionary.csv不同的行如下所示

I'm trying to compare the first columns in two files and print the rows that are different from Dictionary.csv like below

final.csv
d,disease
bc,breast cancer

我试过这个代码。

import csv
with open('English.csv', 'rb') as csvfile1:
    with open ("Dictionary.csv", "rb") as csvfile2:
        reader1 = csv.reader(csvfile1)
        reader2 = csv.reader(csvfile2)
        rows1 = [row for row in reader1]
        rows2 = [row for row in reader2]
        col_a = [row1[0] for row1 in rows1]
        col_b = [row2[0] for row2 in rows2]
        col_c = [row2[1] for row2 in rows2]
        only_b = [text for text in col_b if not text in col_a]

我可以从第一列获得不同的数据,但不能从第二列获得数据,如下所示。如何从第二列获取相应的数据?

I can get data from first column that is different, but not from the second column like below. How can I get the corresponding data from second column?

>>>only_b
['d','bc']


推荐答案

但IMO做你想要的:

import csv
with open('English.csv', 'rb') as csvfile1:
    with open ("Dictionary.csv", "rb") as csvfile2:
        reader1 = csv.reader(csvfile1)
        reader2 = csv.reader(csvfile2)
        rows1_col_a = [row[0] for row in reader1]
        rows2 = [row for row in reader2]
        only_b = []
        for row in rows2:
            if row[0] not in rows1_col_a:
                only_b.append(row)
        print only_b

输出:

[['d', 'disease'], ['bc', 'breast cancer']]

这篇关于比较两个CSV文件并打印不同的Python行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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