Search code examples
stata

Loop for creating several empty csv files


I need to create 215 empty csv files with Stata and save them on my computer.

Since this is a repetitive task, a loop would be perfect. Each file would have a similar but different name (for example Data_Australia, Data_Austria and so on).

How do I create a loop to generate several empty csv datasets with Stata?

I tried the community-contributed command touch but it works well when you only need to generate one empty dataset.


Solution

  • Assuming you want a completely empty file (no header row or anything), just open a file to write to, and immediately close it again.

    cd "C:\Users\My\Directory"
    local country_names Australia Austria "Republic of Korea" // add all the names here 
    foreach country_name in `country_names' {
        file open f1 using "Data_`country_name'.csv", write replace
        file close f1
    }
    

    If you have the names stored as a string variable, say country, you can instead loop through the values in that variable (in this case stopping when it reaches the end or an empty row).

    local row = 1
    while country[`row'] != "" {
        file open f1 using "Data_`=country[`row']'.csv", write replace
        file close f1
        local ++row
    }