Austin
Austin

Reputation: 33

Writing and Reading to/from TAB-delimited CSV files

Purpose: Storing and manipulating data about tips from work in an easy to read format for people. Hence, tab delimited like so:

2017-07-27  THU 16:00-22:00 21.00

I would like to use the CSV.read method to store the information in an array of arrays and that's worked to manipulate it, but I can't figure a good way to write that array back to a TAB delimited file.

How can I write an array of arrays to a txt file in that formatting?

tips = CSV.read("tips.txt",:col_sep => "\t")
CSV.open("tipsoutput.csv","w") do |csv|
csv << tips
end

Gives the output like this:

"[""2017-07-27"", ""THU"", ""16:00-22:00"", ""21.00""]",

Upvotes: 1

Views: 1357

Answers (1)

Simple Lime
Simple Lime

Reputation: 11035

CSV::open can actually take 3 arguments, the third being the csv options (the same for read) so you can just do:

CSV.open("tipsoutput.csv", "w", col_sep: "\t") do |csv|
  csv << ["2017-07-27", "THU", "16:00-22:00", "21.00"]
end

produces the file:

2017-07-27  THU 16:00-22:00 21.00

you will need to iterate through the array, though, as I'm not aware of anything that lets you write multiple arrays (rows) at once, so something like:

CSV.open("tipsoutput.csv", "w", col_sep: "\t") do |csv|
  tips.each { |tip| csv << tip }
end

Upvotes: 1

Related Questions