Ruby:逐行写入 CSV 而不是整个文件

时间:2021-02-19 18:38:38

标签: ruby csv

我正在使用以下代码写入 CSV 文件。它一次写入整个文件。我想通过修改文件逐行写入 CSV 文件。如何调整我的代码?

  CSV.open("#{@app_path}/Data_#{@filename}", "w") do |csv|
    data_array.each do |r|
      csv << r
    end
  end

1 个答案:

答案 0 :(得分:0)

据我所知,问题不在于 csv 文件,而在于数组的大小(每次失败后都必须重建数组)。

我解决这个问题的尝试是按如下块处理数组:


def process_array_by_chunks(array, starting_index = 0, chunk_size)
  return if array.empty?

  current_index = starting_index
  size = array.size
  stop = false

  while !stop do
    puts "doing index: #{current_index}"

    yield(array[current_index, chunk_size])

    stop = true if current_index >= size
    
    current_index = current_index + chunk_size
  end
rescue StandardError => e
  puts "failed at index: #{current_index}"
  puts "data left to process: "
  return array[current_index, size]
end

# call function with a block in which we write csv file
process_array_by_chunks(array, start, chunk_size) do | array|
  CSV.open(path, "w") do |csv|
    array.each do |r|
      csv << r
    end
  end
end

如果由于某种原因而失败,该函数将返回一个包含所有尚未处理的项目的数组。

相关问题