Search code examples
ruby-on-railscsvrake

Data is overwriting instead of appending to CSV


I am using a rake task and the csv module to loop through one csv, extract and alter the data I need and then append each new row of data to a second csv. However each row seems to be overwriting/replacing the previous row in the new csv instead of appending it as a new row after it. I've looked at the documentation and googled but can't find any examples of appending rows to the csv differently.

require 'csv'

namespace :replace do
    desc "replace variant id with variant sku"

    task :sku => :environment do
        file="db/master-list-3-28.csv"

        CSV.foreach(file) do |row|

            msku, namespace, key, valueType, value = row

            valueArray = value.split('|')

            newValueString = ""
            valueArray.each_with_index do |v, index|

                recArray = v.split('*')
                handle = recArray[0]
                vid = recArray[1]
                newValueString << handle
                newValueString << "*"
                variant = ShopifyAPI::Variant.find(vid) 
                newValueString << variant.sku

            end
            #end of value save the newvaluestring to new csv

            newFile = Rails.root.join('lib/assets', 'newFile.csv')

            CSV.open(newFile, "wb") do |csv|
              csv << [newValueString]
            end

        end
    end
end

Solution

  • Your mode when opneing the file is wrong and should be a+. See details in the docs: http://ruby-doc.org/core-2.2.4/IO.html#method-c-new

    Also, you might want to open that file just once and not with every line.