Writing Data to Files

Exercises  1  2
It is often necessary to write data to storage devices. IDL provides several tools to make that relatively easy. The basic operations are
  1. Open a file for writing
  2. Write the data to the file
  3. Close the file
Opening and closing of files are covered in the indicated links. When we want to write to a file, we need to open it for writing or updating, using OPENW or OPENU.

Data is written to a file using the PRINTF statement. The statement may include the FORMAT keyword to control the specific structure of the written file. Format rules are needed when writing an array to a file.

Example 1
Writing data to a file using simple format rules in the PRINTF procedure.

Assume that an array A contains the following data

      10.0000      13.5000      11.0000
      5.00000      19.1000      3.00000
      14.0000      11.9100      4.00000
     -17.0000      5.70000      8.00000
      295.000     -14.2000      6.00000

This array can be written to a file by the following statements. The format statement is a string that includes the parentheses (). Inside are the formatting rules for one row of the output. In this case, each row will contain three numbers that occupy seven characters and have two places after the decimal. The "1x" field specifies a single space between data fields. The result will be an array that has three columns and as many rows as are needed to output all of the array A.

fname='/cis/abc1234/data/data1.dat'
OPENW,1,fname
PRINTF,A,FORMAT='(F7.2,1X,F7.2,1X,F7.2)'
CLOSE,1

Exercise 1
Read the data for the array A from the file exdata.dat in your account and then write it to a file data1.dat in your account. Then open the file in an IDL edit window to see the results. Alternatively, you can use any text display tool in the operating system to show the contents of the file. It contains the data in ASCII text format.

Read about the "F" field of the FORMAT statement in IDL Online Help.

Exercise 2
Use the following statements to write the data to another file. In this case we will make two of the columns such that they contain integer data and one floating point. Read about the "I" field of the FORMAT statement in IDL Online Help.

fname='/cis/abc1234/data/data2.dat'
OPENW,1,fname
PRINTF,A,FORMAT='(I4,1X,F7.2,1X,I2)'
CLOSE,1

Open the file 'data2.dat' in an IDL edit window and examine its structure. How is it different from the file data1.dat?

IDL provides great flexibility in writing data to files by use of the FORMAT keyword in the PRINTF procedure. Over time you should learn about the many options and use them to your advantage.