I'm trying to reorder the columns of a csv file using ruby.
Before:
$ cat foo.csv
foo,bar,foobar
1,2,3,
4,5,6,
7,8,9,
After:
bar,foo,foobar
2,1,3,
5,4,6,
8,7,9,
Unfortunately, when I write out the file, I get extra "," values like so:
bar,foo,foobar
"2,1,3,
","5,4,6,
","8,7,9,
"
Can anyone help me identify why the extra quotation marks are showing up in the csv file?
I'm pretty new to ruby, so I'm open to other ideas if my code is less than ideal.
require 'csv'
acsv = CSV.read("./foo.csv", {headers:true, return_headers:false})
@headers = CSV.open("./foo.csv", 'r', :headers => true).read.headers
# Rearrange headers
temp_index = @headers[0]
@headers[0] = @headers[1]
@headers[1] = temp_index
# Rearrange Columns
acsv.each do |row|
temp_index = row[0]
row[0] = row[1]
row[1] = temp_index
end
puts "acsv is"
puts "#{acsv}"
# Example to write headers http://stackoverflow.com/questions/15905985/how-to-write-columns-header-to-a-csv-file-with-ruby
newcsv = CSV.open("bar.csv", "wb", write_headers: true, headers: @headers) do |csv|
csv << acsv
end
Update Removed unnecessary conversion of headers to headers_array