Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump a 2D array directly into a CSV file?

Tags:

ruby

csv

I have this 2D array:

arr = [[1,2],[3,4]]

I usually do:

CSV.open(file) do |csv| 
  arr.each do |row| 
    csv << row
  end
end

Is there any easier or direct way of doing it other than adding row by row?

like image 598
SwiftMango Avatar asked Jun 05 '12 19:06

SwiftMango


People also ask

How do I convert an array to a CSV file?

To convert an array into a CSV file we can use fputcsv() function. The fputcsv() function is used to format a line as CSV (comma separated values) file and writes it to an open file.

How do I save a NumPy array as a CSV file?

savetext() This method is used to save an array to a text file. Create an array then save it as a CSV file.


1 Answers

Assuming that your array is just numbers (no strings that potentially have commas in them) then:

File.open(file,'w'){ |f| f << arr.map{ |row| row.join(',') }.join('\n') }

One enormous string blatted to disk, with no involving the CSV library.

Alternatively, using the CSV library to correctly escape each row:

require 'csv'
# #to_csv automatically appends '\n', so we don't need it in #join
File.open(file,'w'){ |f| f << arr.map(&:to_csv).join } 

If you have to do this often and the code bothers you, you could monkeypatch it in:

class CSV
  def self.dump_array(array,path,mode="rb",opts={})
    open(path,mode,opts){ |csv| array.each{ |row| csv << row } }
  end
end
CSV.dump_array(arr,file)
like image 100
Phrogz Avatar answered Oct 11 '22 23:10

Phrogz