0

I'm brand new to ruby, and fairly new to programming.

How would you change the headers of a csv file?

foo, bar, foobar
1,   2,   3,
4,   5,   6,
7,   8,   9,

Change to:

herp, derp, herpaderp
1,    2,    3,
4,    5,    6,
7,    8,    9, 

I have found this question, however it doesn't really apply since I'm using the built in 'csv' library instead of the older 'fastcsv' library. (using ruby 2.0.0 on Mac OSX)

What I've tried.

require 'csv'
@filename = ARGV[0]
new_headers = ["herp", "derp", "herpaderp"]

origional_csv = CSV.read(@filename, {headers: true, return_headers: true })
headers = CSV.open(@filename, 'r', :headers => true).read.headers
puts headers

#Change headers to new_headers ? 

Calling test.rb from the command line with foo.csv file

$ ruby test.rb foo.csv
foo, bar, foobar

1 Answer 1

1

You don't even need to do this with the CSV library. Just change the first line of the file, output the rest the same:

lines = File.readlines(@filename)
lines.shift
lines.unshift(["herp", "derp", "herpaderp"].join(',') + "\n")
puts lines.join('')
Sign up to request clarification or add additional context in comments.

2 Comments

I think, update in the same file is not possible partially. Am I right? need to copy data from one file, after processing data, sent those data to a new file..
Update in place isn't possible unless the header text is exactly the same length. It's usually best to re-write to a different file anyway in case you screw something up.

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.