Hi all,

I am trying to append iteration some files (if they exist) belonging to different folders. The folders have the names of Countries and in each folder there are molecules databases (.dta) which might be present in a country but not in another one. What I would like to do is to append molecule I dta in country a to molecule dta of country b (if present).
So say I have two folders called SPAIN and USA. In SPAIN there are a.dta b.ta c.dta; in USA there are k.dta a.dta f.dta c.dta. What I would like to do is to append a.dta of SPAIN with a.dta of USA and c.dta of SPAIN with c.da of USA. The restart the loop and search for k.dta in SPAIN, if not found move to USA, search k.dta, if found the append k.dta of USA with k.dta of the next countries and so on.

Can you please help me?
For the moment I came out with this but it does not seem to work properly::

Code:
cd "/Users/federiconutarelli/Dropbox/PhD/Elasticities/"
local c=0
use "2008_2020_totreshaped.dta", clear
replace Country = subinstr(Country, " R&H", "", .)
replace Country = subinstr(Country, " RETAIL", "", .)
replace Country = subinstr(Country, " COMBINED", "", .)
replace Country = subinstr(Country, " RET", "", .)
replace Country = subinstr(Country, " HOSPITAL", "", .)
quietly levelsof Mole, local(molecules)
    foreach k of local molecules {
        local rex =  strtoname("`k'")
        drop if Country =="ITALY"
        levelsof Countr, local(levels)
        foreach l of local levels {
            local m=0
            capture use "/Users/federiconutarelli/Dropbox/PhD/Elasticities/2008_2020_db/dati_per_paese/data_mole_ctry/`l'/`rex'.dta", clear
            capture append using "/Users/federiconutarelli/Dropbox/PhD/Elasticities/2008_2020_db/data_mole_ctry/`l'/`rex'.dta", gen(appended_`m')
            if _rc ~= 0 {
                continue
            }
            local m=`m'+1
        }
    save "/Users/federiconutarelli/Dropbox/PhD/Elasticities/2008_2020_db/appended_`rex'", replace
}