tags:

views:

148

answers:

2

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  A: 

I think you can change the open to use ab:

CSV.open("t.csv", "ab") do |csv|
Mark Wilkins
+1  A: 

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
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