Last active
May 9, 2022 19:46
-
-
Save bahelms/9fe4d5f2a3bb6706f864 to your computer and use it in GitHub Desktop.
Merge multiple csv files into one in Ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Just thought, since I used this as a starting point and then re-wrote it I would post what I did.