29

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
Mike Woodhouse
  • 51,832
  • 12
  • 88
  • 127
cheolho minale
  • 299
  • 1
  • 3
  • 5

3 Answers3

47

I think you can change the open to use ab:

CSV.open("t.csv", "ab") do |csv|
Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
13

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

File.open("filename", 'a+') {|f| f.write("datatowrite\n)}
Steve
  • 21,163
  • 21
  • 69
  • 92
  • 4
    Note that 'a+' is for read *and* [write/append](http://ruby-doc.org/docs/ProgrammingRuby/html/ref_c_io.html). If you only need to append, then 'a' is sufficient. You can also use [File::APPEND](http://ruby-doc.org/docs/ProgrammingRuby/html/ref_c_file.html), possibly in combination with other mode settings. – Mike Woodhouse Aug 18 '10 at 07:31
  • 1
    We should always use a+ because it will create file if not exists. – user1735921 Oct 10 '17 at 12:30
  • 1
    See [What are the Ruby File.open modes and options?](https://stackoverflow.com/questions/3682359/what-are-the-ruby-file-open-modes-and-options) – BigRon Sep 27 '19 at 21:48
2
File.open('filename', 'a'){ |outfile|
  CSV::Writer.generate(outfile) do |csv|
    csv << ['c1', nil, '', '"', "\r\n", 'c2']
  end
}
rafamart
  • 85
  • 3
  • 2
    AFAIK CSV::Writer is [not available in ruby 1.9](http://stackoverflow.com/a/2140482/514483) – robd Jun 19 '13 at 09:43