Announcement

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

  • Question on looping over files in a directory using local and foreach

    Dear Statalists,

    Recently I am attempting to deal with some .dta files in a local directory on the desktop. I need to amend each file with the same process and append them into a single file. I was trying to use the local and foreach command to loop over the files. However, the code always returns an error of cannot find the file.dta. My code is as the following:

    Code:
    cd "C:\Users\Administrator\Desktop\ICE Monthly data\Datasets"
    local filelist    : dir "C:\Users\Administrator\Desktop\ICE Monthly data\Datasets" file "*.dta"
    foreach file of local filelist{
        use file, clear
        decode _filename, generate(filename)
    }
    Such codes in the do file returns an error mistake of

    file file.dta not found

    I attempted to quote the file in line 3 with single and double quotes but the result remains the same.

    Cai Hanyi

  • #2
    Have you tried this?
    Code:
    use `file', clear

    Comment


    • #3
      You need to use ` (the "back tick") and '(the apostrophe) to dereference your looping macro variable, as must be done whenever you want to use the contents of a local macro.
      Code:
      use "`file'"
      I also wonder if you really want -decode _filename....-, as it would seem unusual to have a filename that was a numeric variable that needed decoding. However, that is not causing your current error message.

      Comment


      • #4
        Originally posted by Mike Lacy View Post
        You need to use ` (the "back tick") and '(the apostrophe) to dereference your looping macro variable, as must be done whenever you want to use the contents of a local macro.
        Code:
        use "`file'"
        I also wonder if you really want -decode _filename....-, as it would seem unusual to have a filename that was a numeric variable that needed decoding. However, that is not causing your current error message.
        Thank you so much for your reply! That code solved my problem.

        As for the -decode- command, this is because those data were imported from .csv files and I incorporated the filename into the data files using -multimport-. The filename is stored as float at that time. Thus, I need to decode it to compile the filenames from different dataset or the first dataset's filename will cover the following ones.

        Cai Hanyi

        Comment

        Working...
        X