1

I have a CSV file that currently does not have any headers. I would like to add a header for the first column. Is there a way to accomplish this in Ruby?

For instance, lets say my CSV looks like this at first:

1,Testing,Testing,New York
2,Testing,Testing,Boston

I want to add a header to the first column so that my csv looks like this:

my_id
1,Testing,Testing,New York
2,Testing,Testing,Boston
Jackson
  • 6,391
  • 6
  • 32
  • 43
  • This could help http://stackoverflow.com/questions/15905985/how-to-write-columns-header-to-a-csv-file-with-ruby – Pavan May 14 '14 at 04:41

2 Answers2

2

Here is one way to do it. The r+ mode to file.open opens for read + write.

file = File.open("data.csv", "r+")
buffer = file.read
file.rewind
file.puts "this is my header"
file.print buffer
file.close
John C
  • 4,276
  • 2
  • 17
  • 28
  • 1
    +1, though consider `file << buffer` or `file.print buffer` instead. `file.puts buffer` adds a newline character if the original file did not end with one (resulting in an empty last line). Not a big deal, but you just want to copy exactly what was already in the file rather than change it in any way. The header does need a newline after it, so `file.puts header` is fine of course. – Daniël Knippers May 14 '14 at 06:49
  • That's a good point. I changed the answer to use file.print instead of file.puts. – John C May 14 '14 at 07:10
0

One possible solution...

$-i = ".orig"
if ARGV.length == 1 || ARGV.length == 2
  header = ARGV.shift
  buffer = ARGF.read
  puts header
  print buffer
else
  STDERR.puts "Must supply one or two command-line arguments:"
  STDERR.puts "\tdesired header (in quotes if it contains spaces)"
  STDERR.puts "\tthe name of the file to prepend the header to"
  STDERR.puts "If the second argument is omitted, reads from STDIN"
end

The $-i will make a backup copy of the original input file with the suffix ".orig" appended, and the original file name will now contain the specified header followed by the original contents.

pjs
  • 18,696
  • 4
  • 27
  • 56