Monthly Archives: February 2013

Tcl Print CSV File

When scripting in Tcl, I often need to process CSV files, including printing it out. Since I often found myself in need of printing, I wrote two helper procedures: load_matrix, which loads a matrix (a table) from CSV file; and print_matrix, which prints a text presentation of the matrix. The end result is the ability for me to print out the contents of a CSV file.


In order to print a CSV file, I first load it up into a matrix using load_matrix, then print it out using print_matrix:

set mx [load_matrix "users.csv"]
print_matrix $mx

Sample CSV File

ID,alias,Full Name
45,alexd,Alexander Dunn
992,alicek,Alice Kim

Sample Output

|ID |alias |Full Name     |
|45 |alexd |Alexander Dunn|
|992|alicek|Alice Kim     |


In my solution, I use three Tcllib packages: csv, struct::matrix, and report. I don’t have to use struct::matrix or report, but they perform the heavy lifting tasks, so I don’t have to.

The Tcl matrix, which really is a table structure with rows, columns, and cells of data; is a great structure for storing the contents of a CSV file. The report package makes it easy to print out the contents of the matrix. The two packages work together seamlessly.

The code at this state works without any error checking, or fancy options. I intentionally keep it simple to demonstrate how it works. I have a few improvements in mind, which I will implement when the need arise:

  • Turn the code into a package
  • Add error checking (i.e. file does not exist)
  • Define different printing styles (HTML table, for example)

Getting The Code

I posted my code at the Tickler Wiki. In the future, I might host it under gitorious, github, or Google Code.