Sumit
Sumit

Reputation: 2023

How to read data from csv file

I am having a csv file Book1.csv. I want to read data so as to use this in my script. I am not able to read in row-column format. Suppose i am having a column named "7-slot" and having data "1 2 3 4 5" and so on. Dont know how to read. Searched from Google and stackoverflow but didnt get.

package require csv
package require struct::matrix

# Load the file into a matrix
struct::matrix data
set f [open Book1.csv]
csv::read2matrix $f data , auto
close $f

This code i have taken from stackoverflow onlt. I am new to TCL so learning these things

Upvotes: 1

Views: 7831

Answers (1)

kostix
kostix

Reputation: 55533

Ah, I think what's missing is adding columns to your matrix before reading into it.

This snippet:

package require csv
package require struct::matrix

struct::matrix m
m add columns 3
set f [open foo.csv]
csv::read2matrix $f m ,
close $f
puts [m serialize]

produces for foo.csv containing

1,2,3
"aaa","bbb","ccc"

this printout:

2 3 {{1 2 3} {aaa bbb ccc}}

Which I parse as "a matrix of 2 rows and 3 columns and then the list of lists which represents rows and column values for each.

Upvotes: 3

Related Questions