I have a short do-file in Stata that uses a loop to read in some datasets, one at a time, and append them to a tempfile. However, this tempfile is not found when trying to open it at the end.
Running this script on Windows and MacOS (Stata 17):
clear
set more off
set trace on
local patha "<patha>"
local pathb "<pathb>"
use "`pathb'fileb.dta", clear
levelsof pathb_variable, local(l)
tempfile append_file
foreach i of local l {
capture confirm file "`patha'filea_`i'.dta"
if _rc==0 {
capture append using `append_file'
save `append_file', replace
}
}
use `append_file', clear
As set trace
is on, I can see that the first line that runs in Stata, before clear
and set more off
is:
do "C:\Users\...\AppData\Local\Temp\10\STD7578_000000.tmp"
on Windows, and
do "/var/folders/02/50xtwnrn5yb_wrh_md7s23br0000gn/T//SD26113.000000"
on Mac.
The error message that appears, just after use `append_file', clear
is run, is:
file C:\Users\...\AppData\Local\Temp\10\ST_7578_000001.tmp not found
on Windows, and
file /var/folders/02/50xtwnrn5yb_wrh_md7s23br0000gn/T//S_26113.000001 not found
on Mac.
In both cases, it looks like a different tempfile being created than is being accessed? The tempfile filename it is trying to open has replaced 'D' with '_' and the last digit is '1' not '0'.
How to make this script work?
I think it is less error prone to save the tempfile as an empty file to append to instead of using capture
without handling the error code.
use "`pathb'fileb.dta", clear
levelsof pathb_variable, local(l)
tempfile append_file
preserve
clear
save `append_file', emptyok
restore
foreach i of local l {
capture confirm file "`patha'filea_`i'.dta"
if _rc==0 {
append using `append_file'
save `append_file', replace
}
}
use `append_file', clear