Python比较两个CSV文件时,行顺序无关紧要 [英] Python comparing two CSV files when order of rows doesn't matter

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

问题描述

我有一些代码可以创建一个CSV文件。它写入文件的行的顺序可以不同。我写一个测试,以确保CSV文件是我所期望的。所有我需要做的是检查所有行是否存在和所有字段相等。我有下面的代码,但不知道如何让它工作,所以它不关心行的顺序。如何确保两个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)

这篇关于Python比较两个CSV文件时,行顺序无关紧要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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