Search code examples
gretl

append within loop: Skipping non-existing files


This question is related to: Import timeseries via loop (pot. generic)

I want to import an arbitrary number of files posited in the same directory, but not continuously labelled, e.g.: file_1,file_4,file_3001

I have a small import script that works for consecutive files similar to the following:

scalar first = 1 #the first file is file_1.tsv
scalar last = 5000 #the last file
base_path = "c:/results/file_"
sprintf temp_path "%s%d.tsv",base_path,first
open @temp_path --preserve
setobs 1 1 --special-time-series    
loop for (i=first+1;i<=last;i+=1) --quiet
    sprintf temp_path "%s%d",base_path,i
    append @temp_path 
endloop

Now, when I use it on a setting as above (with missing files) I get an error and the script stops:

Couldn't open ...

is it possible to somehow proceed / catch the error and "continue" ?


Solution

  • I think the "catch" command can do what you need. Take a look at the following code:

    # Creating files
    open australia.gdt
    store 0.gdt PAU
    store 1.gdt PUS
    store 2.gdt E
    store 4.gdt IAU
    store 8.gdt IUS
    store 10.gdt le
    
    # Opening created files
    open 0.gdt
    loop i = 1..10
        catch append $i.gdt
    endloop