-
-
Save electron0zero/1e12a74ee4b996bb2da2ed90a583cf1d to your computer and use it in GitHub Desktop.
Merge multiple csv files into one in Ruby
This file contains hidden or 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