我有一个包含许多列的“主”文件:1 2 3 4 5。我还有一些其他文件,其行数比主文件少,每个文件的列数:1 6。我想合并这些匹配的文件在第 1 列字段上并将第 6 列添加到主字段。我见过一些 python/UNIX 解决方案,但如果合适的话我更喜欢使用 ruby/fastercsv。我将不胜感激任何入门帮助。
FasterCSV 现在是 Ruby 1.9 中默认的 CSV 实现。该代码未经测试,但应该可以工作。
require 'csv'
master = CSV.read('master.csv') # Reads in master
master.each {|each| each.push('')} # Adds another column to all rows
Dir.glob('*.csv').each do |each| #Goes thru all csv files
next if each == 'master.csv' # skips the master csv file
file = CSV.read(each) # Reads in each one
file.each do |line| #Goes thru each line of the file
temp = master.assoc(line[0]) # Finds the appropriate line in master
temp[-1] = line[1] if temp #updates last column if line is found
end
end
csv = CSV.open('output.csv','wb') #opens output csv file for writing
master.each {|each| csv << each} #Goes thru modified master and saves it to file
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)