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.

Usage

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     |
+===+======+==============+

Discussion

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.

2 thoughts on “Tcl Print CSV File

  1. Nagu

    There can’t be a better timing than this. Just couple of days back, I was searching for a tutorial on _report_ package. Thanks a lot.

  2. subrat

    Hi,

    Thanks in advance.
    using the below statement to create a .csv file .
    set f [open rp_summary.csv w+]

    could you suggest how to tab in the .csv file.

    Thanks
    Subrat

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s