Coyote's Guide to IDL Programming

Creating Comma Separated Value Files

QUESTION: Can you show me how to write my IDL array out to a comma separated value file I can easily load into my spreadsheet?

ANSWER: The trick to writing comma separated value files (*.csv) is to add the comma to each value in an IDL array. There are probably a number of different methods to do this, but here is one I use successfully. What I do is turn the 2D data array into a string array, add the commas to the string array, then write the string array out to a data file.

The heart of the matter lies in code that looks something like this. Notice the Width keyword on the OpenW command. This is necessary to get a full line of output. A line width of 1600 characters (as opposed to the default line width of 80 characters) is usually enough for most arrays that I am writing to spreadsheets.

   ; Set up variables.
   filename = 'test.csv'
   s = Size(data, /Dimensions)
   xsize = s[0]
   lineWidth = 1600
   comma = ","

   ; Open the data file for writing.
   OpenW, lun, filename, /Get_Lun, Width=lineWidth

   ; Write the data to the file.
   sData = StrTrim(data,2)
   sData[0:xsize-2, *] = sData[0:xsize-2, *] + comma
   PrintF, lun, sData

   ; Close the file.
   Free_Lun, lun

I have written a program named Write_CSV_Data that will allow you to write a 2D array and an optional vector of column headers to a CSV file. The program is written in such a way that you can use any string delimiter, including a comma, which is the default.

Timm Weitkamp points out that another way of adding a comma to the numbers is to use the "colon" format code in the PrintF comand. The colon format code supresses the comma following the last number in the row. So the procedure above would look like this:

   ; Set up variables.
   filename = 'test.csv'
   s = Size(data, /Dimensions)
   xsize = s[0]
   lineWidth = 1600

   ; Open the data file for writing.
   OpenW, lun, filename, /Get_Lun, Width=lineWidth

   ; Write the data to the file.
   theFormat = '(' + StrTrim(xsize,2) + '(F, :, ","))'
   PrintF, lun, data, Format=theFormat

   ; Close the file.
   Free_Lun, lun

Google
 
Web Coyote's Guide to IDL Programming