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

Example pages containing: tips | resources | functions/procedures

Writing ASCII data

NCL's ability to write out ASCII data used to be limited. Previously, the only option available was to use the function asciiwrite, which is restricted to writing ASCII files with one entry per line.

In NCL V6.1.0, we added write_table, which allows you to format mixed type data with a single format statement and write it to a file.

If you don't have mixed types, you can use the write_matrix procedure, which allows you to write nicely-formatted integer, float, or double precision two-dimensional (2D) arrays to standard out or to an ASCII file. write_matrix also allows the user to control the format of the written data.

In general, if one wishes to output a 1D time series, asciiwrite should be used. If the user wishes to have control over the format of the written data, or wishes to output 2D arrays, then write_table or write_matrix should be used.

Below are two methods you can use for writing mixed data to a file. The first method uses write_table, which you must have NCL V6.1.0 to run. The second method uses a combination of sprintf and sprinti. They both produce the same ASCII file, "file.txt".

Method 1 (easier, but requires NCL V6.1.0 or later)

load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"

begin
;---Generate some dummy integer and float data.
   npts = 100
   i    = ispan(1,npts,1)
   j    = generate_unique_indices(npts)
   k    = generate_unique_indices(npts)
   x    = random_uniform(-10,10,npts)
   y    = random_uniform(0,1000.,npts)

  write_table("file.txt","w",[/j,x,i,y,k/], \
              "string_%03i %8.2f %4.0i %8.1f     string_%03i")
end

Method 2

load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"

;---Generate some dummy integer and float data.
   npts = 100
   i    = ispan(1,npts,1)
   j    = generate_unique_indices(npts)
   k    = generate_unique_indices(npts)
   x    = random_uniform(-10,10,npts)
   y    = random_uniform(0,1000.,npts)

   lines = "string_" + sprinti("%03i", j) + \
           sprintf("%8.2f",x) + \
           sprinti("%4.0i", i) + \           
           sprinti("%4.0i", i) + " " + \           
           sprintf("%8.1f",y) + \
           "    string_" + sprinti("%03i", k)

;---Write to a file
  asciiwrite("file.txt",lines)

Here's a sample of the first few lines of the "file.txt" file:

string_031   -0.11   1   269.1    string_040
string_074    5.17   2   798.3    string_018
string_015    8.73   3   408.6    string_082
string_037    2.14   4   546.1    string_054