Hello everyone,
I am trying to import several CSV files into Stata, retain specific variables, and then append all the files together into one dataset. However, I am encountering an error where Stata can't find the directory. I suspect that the issue might be with the way I'm referencing the folder paths, but I am not sure what the exact problem is. Could anyone help me understand what might be causing the error and suggest a solution?
global main_directory "C:\Users\fimi\Desktop\TEST"
local subfolders BaseA BaseB
clear
foreach subfolder of local subfolders {
local path "$main_directory\\`subfolder'"
local files: dir "`path'" files "CR_Base_A_*.csv"
foreach file of local files {
di "Importing file: `file'"
import delimited "`path'\\`file'", clear
keep Name Ownership CIK
append using "`path'\\`file'", force
di "Appended file: `file'"
}
}
save "$main_directory\\Appended_Data.dta", replace
I am trying to import several CSV files into Stata, retain specific variables, and then append all the files together into one dataset. However, I am encountering an error where Stata can't find the directory. I suspect that the issue might be with the way I'm referencing the folder paths, but I am not sure what the exact problem is. Could anyone help me understand what might be causing the error and suggest a solution?
- The main folder is named "TEST".
- Inside the "TEST" folder, there are two subfolders: "BaseA" and "BaseB".
- Each subfolder contains 35 CSV files.
- The files in BaseA have names that begin with "CR_Base_A_" and end with a date (e.g., CR_ADV_Base_A_20220101.csv).
- I want to:
- Import all these files into separate Stata files and save them.
- Then keep the variables "Name", "Ownership", and "CIK" from each file and then append all into one combined dataset.
global main_directory "C:\Users\fimi\Desktop\TEST"
local subfolders BaseA BaseB
clear
foreach subfolder of local subfolders {
local path "$main_directory\\`subfolder'"
local files: dir "`path'" files "CR_Base_A_*.csv"
foreach file of local files {
di "Importing file: `file'"
import delimited "`path'\\`file'", clear
keep Name Ownership CIK
append using "`path'\\`file'", force
di "Appended file: `file'"
}
}
save "$main_directory\\Appended_Data.dta", replace
Comment