【问题标题】:Append to csv only if row doesn't exist仅当行不存在时才附加到 csv
【发布时间】:2017-03-20 16:12:30
【问题描述】:

我的代码看起来像

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

假设在迭代中的某个时刻,object1 的值为 1object2 的值为 2object3 的值为 3
如果有一行,是否可以签入我的test.csv 文件

1,2,3

已经存在,所以不要再次将同一行附加到我的 csv 文件中?

【问题讨论】:

    标签: ruby csv duplicates append unique


    【解决方案1】:
    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
    

    【讨论】:

    • 未定义方法“排除?”对于 #<...>
    【解决方案2】:

    这就是我的做法

        existing_dates = Array.new
        file = File.open(@renko_csv_path, "r")
        file.each_line do |a|
          fields = a.split(',')
          date = fields[0].tr_s('"', '').strip
          existing_dates.push(date)
        end
        renko_points.each do |renko_hash|
          CSV.open(@renko_csv_path,  (File.file?(@renko_csv_path) ? "ab" : "wb")) do |csv|
            if !existing_dates.include?(renko_hash[:date])
              csv << renko_hash.map { |key, value| value }
            end
          end
        end
    

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2016-10-19
      • 2021-01-08
      • 2021-11-16
      相关资源
      最近更新 更多