2

While I'm appending data to csv in a loop headers also getting appended in csv file, for example consider below query

10.times do 
   CSV.open("file_name", "ab", write_headers: true, headers: ["team", "points"]) do |csv|
     csv << ["SRH","20"]   
   end
end

Resulting CSV will have alternate headers and alternate values. How to prevent appending headers multiple times? Thanks in advance.

2
  • You're opening the same csv file in every loop, do you definitely want to do that? Commented May 18, 2016 at 16:37
  • I don't mean I would append in loop, in runtime I would be appending to the existing file multiple times Commented May 18, 2016 at 16:45

1 Answer 1

1

You are opening up your csv file and adding data in a loop. You want to open your file ones and then add any data in a loop.

CSV.open("file_name", "ab", write_headers: true, headers: ["team", "points"]) do |csv|
   10.times do 
     csv << ["SRH","20"]   
   end
end

The output is:

team,points
SRH,20
SRH,20
SRH,20
SRH,20
SRH,20
SRH,20
SRH,20
SRH,20
SRH,20
SRH,20
Sign up to request clarification or add additional context in comments.

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.