Sun
Sun

Reputation: 179

Stata how to export delimited files using 'file` in a loop

I'm importing dta files in a folder and exporting each to a csv file. I'm not sure why but the loop doesn't save the file. Here's the code:

global path "file path"
cd "${path}"

* Geocodes for edd
clear
local files: dir "${path}Data\MeasureData\" files "*_edd.dta"

*do loop to bridge file for EDD and 
foreach file in `files' {

    use "${path}Data/MeasureData/`file'", clear
    rename beafips edd_id
    merge m:1 edd_id using Data\TempData\bridge_edd.dta
    keep if _merge==3
    drop _merge
    export delimited "${path}Data\OutgoingData\`file'.csv", replace
    
}

I keep getting error like this:

file filepath\Data\OutgoingData.csv saved

I was expecting this to be saved as filepath\Data`file'.csv. What did I do wrong?

Upvotes: 0

Views: 371

Answers (1)

C.Robin
C.Robin

Reputation: 1102

This is happening because Windows defaults to using backslashes in path directories, but in this context your computer is reading the backslash as an escape character and so isn't interpreting the ` as indicating the beginning of your local files.

This problem won't typically appear on a Mac/Linux machine as they default to using forward slashes in directory paths.

So the solution is to change all the \s to /s in your code. See here for a more detailed write-up of the problem: https://journals.sagepub.com/doi/pdf/10.1177/1536867X0800800310

Upvotes: 4

Related Questions