Skip to content

Instantly share code, notes, and snippets.

@electron0zero
Forked from bahelms/merge_csv.rb
Created March 19, 2018 06:58
Show Gist options
  • Select an option

  • Save electron0zero/1e12a74ee4b996bb2da2ed90a583cf1d to your computer and use it in GitHub Desktop.

Select an option

Save electron0zero/1e12a74ee4b996bb2da2ed90a583cf1d to your computer and use it in GitHub Desktop.
Merge multiple csv files into one in Ruby
require "csv"
def csv_headers
["Your", "Headers", "Here"]
end
files = Dir["file_names_*.csv"].sort_by { |f| "if you want to sort the files" }
file_contents = files.map { |f| CSV.read(f) }
csv_string = CSV.generate do |csv|
csv << csv_headers
file_contents.each do |file|
file.shift # remove the headers of each file
file.each do |row|
csv << row
end
end
end
File.open("one_csv_to_rule_them_all.csv", "w") { |f| f << csv_string }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment