marcamillion marcamillion - 1 month ago 20
Ruby Question

How do I write a header to an existing CSV?

I have a directory with a bunch of CSV files with no headers.

I tried doing it like this:

def add_headers_to_csvs
csvs = Dir["#{@dir_name}/#{@state}/*.csv"]
csvs.each do |csv_file|
CSV.open(csv_file, "a+", write_headers: true, headers: ["Company_Name","Website","Street_Address", "City", "State", "Zip", "Phone","Email"]) do |csv|
end
end
end


I was hoping that the
write_headers
and
headers:
option would work and it doesn't.

How do I accomplish what I am trying to do?

Answer

You can't just re-open them in place, especially in append mode. You'll need to open a new file, write the headers, then append all of the original data as well.

Normally you'd do this with a temporary file of some sort:

CSV.open(csv_file + '.tmp', 'w', write_headers: true, headers: [ ...]) do |dest|
  # Transpose original data
  CSV.open(csv_file) do |source|
    source.each do |row|
      dest << row
    end
  end
end

# Swap new version for old
File.rename(csv_file + '.tmp', csv_file)

Now you'll absolutely want to have backups of your original data in case something goes horribly wrong.

Comments