Append row to csv file Ruby 1.9 CSV lib

我只是一个虾纸丫 提交于 2019-12-09 07:41:18

问题


Using Ruby 1.9 and CSV lib, I can't seem to append a row. The example in the documentation opens the file, and overwrites the row. What is the correct way to append rows to the document?

Example from documentation:

require 'csv'
CSV.open("path/to/file.csv", "wb") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

回答1:


I think you can change the open to use ab:

CSV.open("t.csv", "ab") do |csv|



回答2:


I will usually use the following to write to a csv file (Or any file)

File.open("filename", 'a+') {|f| f.write("datatowrite\n)}



回答3:


File.open('filename', 'a'){ |outfile|
  CSV::Writer.generate(outfile) do |csv|
    csv << ['c1', nil, '', '"', "\r\n", 'c2']
  end
}


来源:https://stackoverflow.com/questions/3507602/append-row-to-csv-file-ruby-1-9-csv-lib

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!