如何比较两个CSV文件中的数据 [英] How to compare data in two CSV files

查看:1139
本文介绍了如何比较两个CSV文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个CSV文件具有相同的结构,理想情况下应该有相同的数据。

I have two CSV files which have the same structure and ideally should have the same data.

我想使用Ruby比较它们中的数据,想知道我们是否已经有一个Ruby函数。

I want to compare the data in them using Ruby and wanted to know if we already have a Ruby function for the same.

推荐答案

正如Summea评论,看看 CSV 类。

As Summea commented, look at the CSV class.

然后使用:

#Will store each line of each file as an array of fields (so an array of arrays).
file1_lines = CSV.read("file1.csv")
file2_lines = CSV.read("file2.csv")

for i in 0..file1_lines.size
  if (file1_lines[i] == file2_lines[i]
    puts "Same #{file1_lines[i]}"
  else
    puts "#{file1_lines[i]} != #{file2_lines[i]}"
  end
end

在Ruby中是很少见的,你通常在集合上使用每个进行迭代,但是这里有两个。

Note that using for in Ruby is quite rare. You normally iterate using an each on the collections, but there are two of them here.

此外,请注意,列表中的一个可能比另一个长,但这应该让你开始。

Also, pay attention that one of the list may be longer than the other, but this should get you started.

这篇关于如何比较两个CSV文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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