Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • import many csv files

    Dear All, I generate many csv and excel files as
    Code:
    cd "E:\Stata\import data\manycsv"
    
    webuse grunfeld, clear
    
    preserve
    keep if company == 1
    export excel using "a1.xls", firstrow(variables) replace
    export delimited using "a1.csv", replace
    restore
    
    preserve
    keep if company == 2
    export excel using "b2.xls", firstrow(variables) replace
    export delimited using "b2.csv", replace
    restore
    
    preserve
    keep if company == 3
    export excel using "c3.xls", firstrow(variables) replace
    export delimited using "c3.csv", replace
    restore
    I tried to follow the thread (https://www.statalist.org/forums/for...many-csv-files) to import those generated csv files as
    Code:
    // ssc inst fs 
    clear
    cd "E:\Stata\import data\manycsv"
    fs *.csv 
    foreach f in `r(files)' {   
      insheet using "`f'", clear 
      *local ID: subinstr local f "NYSE_" "", all 
      save "`f'.dta", replace
    }
    I have "a1.csv.dta, b2.csv.dta, and c3.csv.dta. How can I modify the code to get resulting files as a1.dta, b2.dta, and c3.dta? Thanks.
    Ho-Chuan (River) Huang
    Stata 17.0, MP(4)

  • #2
    This should do it:
    Code:
    // ssc inst fs 
    clear
    cd "E:\Stata\import data\manycsv"
    fs *.csv 
    foreach f in `r(files)' {   
      insheet using "`f'", clear 
      *local ID: subinstr local f "NYSE_" "", all
      local newname: subinstr local f ".csv" ""
      save "`newname'.dta", replace
    }

    Comment


    • #3
      Dear Clyde, It works just fine. Thanks for your helpful suggestion.
      Ho-Chuan (River) Huang
      Stata 17.0, MP(4)

      Comment

      Working...
      X