Output Array to CSV in Ruby

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
csv << ["row", "of", "CSV", "data"]
csv << ["another", "row"]
# ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

convert array to CSV file on ruby

I managed to do this with(2nd edit) proper indentation

headers = ["user_id", "created_at"]
CSV.open("myfile.csv", "w", :col_sep => "\t| ", :headers => true) do |csv|
csv << headers
csv << ["-"*(headers.join.length+4*headers.length)] #Header separator in the length of header columns + tabs
a.each {|row| csv << row } #Adding rows for each element of a
end

Writing array into csv file

How about this? CSV creation outside the results loop.

require 'tiny_tds'
require 'csv'

db_host = 'myserver.com'
db_user = 'mylogin'
db_pass = 'mypassword'
client = TinyTds::Client.new(:host => db_host, :username => db_user, :password => db_pass)
results = client.execute("SELECT * FROM mydatabase")

CSV.open("data.csv", "wb") do |csv|
results.each do |row|
csv << row.to_a
end
end

Write an array to multi column CSV format using Ruby

Alternately using the CSV Class:

  def write_to_csv(row)
if csv_exists?
CSV.open(@csv_name, 'a+') { |csv| csv << row }
else
# create and add headers if doesn't exist already
CSV.open(@csv_name, 'wb') do |csv|
csv << CSV_HEADER
csv << row
end
end
end

def csv_exists?
@exists ||= File.file?(@csv_name)
end

Call write_to_csv with an array [col_1, col_2, col_3]

Wrapping output of an array to CSV conversion in quotations in Ruby

You can pass the :force_quotes option to the CSV library to have it quote everything in the csv for you:

base_options = {headers: ['first,col', 'second column'], write_headers: true}
options = [{}, {force_quotes: true}]

data = [
['a', 'b'],
['c', 'd'],
['e', 'f']
]

options.each do |option|
result = CSV.generate(base_options.merge(option)) do |csv|
data.each do |datum|
csv << datum
end
end

puts "#{option}:\n#{result}"
end

For instance, in this small script, by default, the only thing that gets quoted is the first column header because it contains a comma. By passing in force_quotes: true, in the second pass though, everything gets quoted.

Output:

{}:
"first,col",second column
a,b
c,d
e,f
{:force_quotes=>true}:
"first,col","second column"
"a","b"
"c","d"
"e","f"

Output many arrays to CSV-files in Ruby

You need to put the iteration inside the open CSV file:

CSV.open("#{foobar}_new.csv", "w") do |csv|
arr.each { |p|
csv << p.print_csv_record
}
end

Ruby 2d array to csv?

You are not writing to file.

require 'csv'
CSV.open('file.csv', 'w') do |csv|
arr1.each { |ar| csv << ar }
end


Related Topics



Leave a reply



Submit