python compare 打印差异_比较两个CSV文件并打印不同的Python行

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

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

I tried this code.

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

解决方案

Not sure how effective is this but IMO does what you want:

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

Outputs:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值