fabersky fabersky - 26 days ago 9
Ruby Question

Append to csv only if row doesn't exist

My code looks like

CSV.open("test.csv", "a+") do |csv|
(0..array.count).each do
csv << [object1, object2, object3]
end
end


Let's say at some point in the iteration,
object1
has value
1
,
object2
has value
2
and
object3
has value
3
.

Is it possible to check in my
test.csv
file if a row

1,2,3


already exists, and so don't append the same row again to my csv file?

Answer
csv_file = 'test.csv'
existing_lines = File.readlines(csv_file).map(&:strip) # remove line breaks

CSV.open(csv_file, 'a+') do |csv|
  (0..array.count).each do
    data = [object1, object2, object3]
    str = data.join(',')
    unless existing_lines.include?(str)
      csv << data
      existing_lines << str
    end
  end
end
Comments