idlidl-programming-language

reading and writing multiple data files in idl


I'm new to IDL and trying to read multiple binary data files from a certain folder and write them in a text format to a certain folder all at once. I currently have a code that reads and writes only one file at a time and I have to do the naming manually,but I need to read and write all the files at once to avoid naming errors when reading one by one manually. here is my code please assist.I need to read and write the multiple data files all at once.

    pro readfitacf

; Open the raw file for read only 


  inp=FitOpen('/media/New Volume/SANAE/2010_fitacf/2010 Jan/20100114.0931.17.san.fitacf',/read)


;  Search for a specific time in the file

;prm.bmnum = 15

;prm.nrang = 5

filename = '/project/2010 Jan/20100114.0931.17.san.txt'

OPENW,5,filename

where Fitopen is a function as follows


      function FitOpen,fname,atme=atme,lib=lib, $
               native=native,external=external, $
                read=read,write=write,update=update
mode=0

if (KEYWORD_SET(lib) eq 0) then lib=getenv('LIB_FITIDL')

if KEYWORD_SET(native) then mode=1

if KEYWORD_SET(external) then mode=2

if (mode eq 0) and (file_test(lib) eq 1) then mode=2 $

else if (mode eq 0) then mode=1


if (mode eq 1) then begin

if KEYWORD_SET(read) then openr,unit,fname,/GET_LUN,/SWAP_IF_BIG_ENDIAN

if KEYWORD_SET(write) then openw,unit,fname,/GET_LUN, /SWAP_IF_BIG_ENDIAN

if KEYWORD_SET(update) then openu,unit,fname,/GET_LUN, /SWAP_IF_BIG_ENDIAN

endif else begin

if KEYWORD_SET(read) then openr,unit,fname,/GET_LUN,/STDIO

if KEYWORD_SET(write) then openw,unit,fname,/GET_LUN,/STDIO

if KEYWORD_SET(update) then openu,unit,fname,/GET_LUN,/STDIO

endelse


return, unit

end

Solution

  • You can use FILE_SEARCH to search for specific files with a pattern and get an array of file paths. Then, just loop over this array. To get the base name of the file use for example FILE_BASENAME:

    files = FILE_SEARCH('directory1/*.fitacf')
    
    FOR i = 0, N_ELEMENTS(files) - 1 DO BEGIN
        inp=FitOpen(files[i],/read)
        filename = 'directory2/'  + FILE_BASENAME(files[i], '.fitacf') + '.txt'
        OPENW, unit, filename, /GET_LUN
        ; do stuff
        FREE_LUN, unit, inp
    ENDFOR