Reputation: 89
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.
Upvotes: 2
Views: 421
Reputation: 11813
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
Upvotes: 1