python逐行比较两个csv,Python比较两个CSV文件时,行顺序无关紧要

I have some code that creates a CSV file. The order of the rows it writes to the file can vary. I am writing a test to make sure the CSV file is what I expect. All I need to do is check that all rows are present and all fields equal. I have the code below, but am not sure how to get it to work so it doesn't care about the order of the rows. How can I make sure two CSV files contain the same rows, but the order of the rows doesn't matter?

def assertRowsEqual(self, first, second)

error_count = 0

first_f = open(first)

csv1 = csv.reader(first_f, delimiter=',', quotechar='"',

quoting=csv.QUOTE_ALL)

second_f = open(second)

csv2 = csv.reader(second_f, delimiter=',', quotechar='"',

quoting=csv.QUOTE_ALL)

for row1 in csv1:

row2 = csv2.next()

if row1 != row2:

self.fail("NOT THE SAME\n")

解决方案

If you don't care about repeated rows:

set(csv1) == set(csv2)

else:

sorted(csv1) == sorted(csv2)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值