【问题标题】:Compare two CSV files and print the rows that are different Python比较两个 CSV 文件并打印不同 Python 的行
【发布时间】:2015-01-20 01:48:21
【问题描述】:

我正在尝试比较两个如下所示的 csv 文件

English.csv
i
am
is
was
were

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

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

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]

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

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

【问题讨论】:

    标签: python csv compare diff with-statement


    【解决方案1】:

    不确定这有多有效,但 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']]
    

    【讨论】:

      猜你喜欢
      • 2016-12-24
      • 2020-12-29
      • 2017-07-30
      • 2013-06-17
      • 1970-01-01
      • 2022-11-15
      • 2023-02-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多