比较两个CSV文件并打印不同的行 - Python

2024-05-20 08:01:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图比较两个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']

Tags: 文件csvtextinfordictionaryenglishcol
1条回答
网友
1楼 · 发布于 2024-05-20 08:01:16

我不知道这有多有效,但我想做的是:

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

相关问题 更多 >