X
120 Rate this article:
No rating

[Internal] A Simple IDL Code Example to WRITE into an Formatted ASCII file

Anonym

The following example code shows how to read from an ASCII file, do some calculations with the data and then, write the results in a new ASCII file.


PROCEDURE

The IDL example procedure that follows is devided in three parts:

1- Read the ASCII file called cities.txt. This is a simple text file that contains the name and positions of several world cities. A short view of the file is this:

Adelaide         -34.55   138.34

Anchorage        61.12  -149.48

Athens              38.00    23.38

Auckland        -36.53   174.45

2- count the number of lines in the file, using:

FILE_LINES()

3- Open the file in a generic logical unit:

OPENR, lun, file, /get_lun

4- Read the contents of the file using a FOR loop

5- Looking for the cities where the latitudes are negative, using the WHERE function:

i_south    = WHERE(lat lt 0.0)

6- Open a new file where the new list will be saved:

fname='south_cities.dat'

OPENW, 1, fname

7- Use the PRINTF procedure to save the information into columns and headers, using as well the FORMAT keyword. The final result will look like this:

Cities in the Southern Hemisphere

   lat           lon           name
   ---          ---            ----
-149.48    61.12       Anchorage      
 -71.07     42.15       Boston         
-105.19    40.02       Boulder        
 -58.30    -34.20       Buenos Aires   
 -66.58      10.30      Caracas        
  -7.41       33.32      Casablanca     
 -87.37      41.49      Chicago        
 -96.48      32.45      Dallas         
 

The following is the full IDL example procedure:


pro write_ascii_file

compile_opt idl2

;; Locate the file on the file system.
file = 'cities.txt'

;; The number of header lines and data records in the file.
n_fields = 3
n_recs   = file_lines(file)

;; Define a data format for the file.
s0 = ''
f0 = 0.0
f1 = 0.0
city = strarr(n_recs)
lon  = fltarr(n_recs)
lat  = fltarr(n_recs)

;; Open the file for reading.
openr, lun, file, /get_lun

;; Read the contents of the file.
for i = 0, n_recs-1 do begin
  readf, lun, s0, f0, f1, format='(a15,f7.2,2x,f7.2)'
  city[i] = s0
  lon[i]  = f0
  lat[i]  = f1
endfor

i_south    = where(lat lt 0.0)
city_south = city[i_south]
lon_south  = lon[i_south]
lat_south  = lat[i_south]

n_south   = n_elements(city_south)

fname='south_cities.dat'
OPENW, 1, fname

PRINTF, 1, FORMAT='("Cities in the Southern Hemisphere")'
PRINTF, 1
PRINTF, 1, FORMAT='(3x, "lat", 5x, "lon", 4x, "name")'
PRINTF, 1, FORMAT='(3x, "---", 5x, "---", 4x, "----")'
for i=0, n_south-1 do begin
  PRINTF, 1, lat_south[i], lon_south[i], city_south[i], FORMAT='(2(F7.2,1X), a15)'
endfor

CLOSE,1

;; Close the file.
free_lun, lun
end

NOTE: The above code was based in an original code by Mark Piper, written for the Introduction to IDL class.