Dynamo
Dynamo

Reputation: 137

How to write CSV file form the beginning in TCL, I have a data in rows

How to write CSV files in TCL, I have data which I need to put in CSV file I never worked with CSV before.

Upvotes: 1

Views: 3934

Answers (2)

glenn jackman
glenn jackman

Reputation: 247012

CSV is surprisingly tricky to work with. You can't just blindly join elements with a comma, because the data might have commas in it:

set data {42 "value,with,commas" {value "with quotes"}}
puts [join $data ,]
42,value,with,commas,value "with quotes"

That's not the right number of fields. So, let's quote every element.

puts [join [lmap elem $data {format {"%s"} $elem}] ,]
"42","value,with,commas","value "with quotes""

But now the inner quotes are broken, so the CSV convention is to double the double quotes.

puts [join [lmap elem $data {format {"%s"} [string map {{"} {""}} $elem]}] ,]
"42","value,with,commas","value ""with quotes"""

This is now correct CSV, if overly quoted. Or, as Colin said, use csv

package require csv
puts [csv::join $data]
42,"value,with,commas","value ""with quotes"""

Or, if you already have a list of lists representing your data

set data2 {{a b c} {d e f} {g h i}}
puts [csv::joinlist $data2]
a,b,c
d,e,f
g,h,i

Upvotes: 2

Colin Macleod
Colin Macleod

Reputation: 4382

Take a look at the CSV module in Tcllib

Upvotes: 1

Related Questions