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
1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

+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.
That's a good point. I changed the answer to use file.print instead of file.puts.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.