当行顺序无关紧要时,Python 比较两个 CSV 文件
我有一些创建 CSV 文件的代码。写入文件的行的顺序可能会有所不同。我正在编写一个测试以确保 CSV 文件符合我的预期。我需要做的就是检查所有行是否都存在并且所有字段是否相等。我有下面的代码,但不确定如何让它工作,所以它不关心行的顺序。如何确保两个 CSV 文件包含相同的行,但行的顺序并不重要?
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")
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")
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不关心重复的行:
else:
If you don't care about repeated rows:
else:
如果它们适合内存,只需将其转换为列表并对其进行排序即可。
If they'll fit in memory, just cast to lists and sort them.