如何比较两个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.