NCL Website header
NCL Home> Application examples> File IO || Data files for some examples

Example pages containing: tips | resources | functions/procedures

Writing CSV (comma-separated values) files

CSV files are ASCII files whose values are separated by commas or other separators (semicolons, spaces, etc).

You can write CSV files using a combination of one or more of these functions:

  • write_table - this is the best function to use, as it allows you to write mixed data types and to append to an existing file.

  • asciiwrite - an older and rather limited function that writes one value per line. This is useful for outputting a one-dimensional time series.

  • sprintf / sprinti - allows you to format integer and float data before writing with write_table or asciiwrite.

For examples of reading or writing other types of ASCII files, see:

write_csv_1.ncl: Shows how to create this very simple CSV file:

Each of the three columns of data are stored in their own variable in the NCL script.
write_csv_2.ncl: Shows how to read data off a NetCDF file and write to a CSV file using write_table. A header is written using the long_name and units attributes for each variable.

Seven variables are written, three of which are 4D arrays dimensioned time x lev x lat x lon, and have to be converted to 1D arrays in order to write them as single columns. The other four variables are the 1D coordinate arrays (time, lev, lat, and lon) which have to be conformed to 4D arrays using conform_dims, before writing them along with the other 4D arrays.

write_csv_3.ncl: Shows how to write data of mixed types to a CSV file using write_table. A header is also written, with each field name enclosed in double quotes.

This example uses the following format string to write a mix of floats, integers, and strings to the file:

  format = "%2d,%6.2f,%7.2f,%4d,%s,%1d"

The resultant "example3.csv" file should look like this:

 4,-27.75, 152.45,-999,ADAM,0
 5,-27.03, 152.02,-999,MARY,0
 6,-26.76, 148.82,-999,DAVE,1
 7,-26.58, 148.77,-999,RICK,0
 8,-26.48, 148.68,1000,DENNIS,0
 9,-26.30, 148.52, 900,TIM,0
10,-26.25, 148.41,-999,SPONGEBOB,0

If you don't want any spaces in your CSV file, then don't specify any kind of field lengths in the format string:

  format = "%d,%g,%g,%g,%s,%d"

The resultant file would then look like this: