Announcement

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

  • Error looping over filename

    Hi

    Stata reports "...file not found" when I try to do the following. I have a few CSV files that I want to import, do a few things and then reshape and save as Stata dta files. Here is the most basic version of what I am doing.

    Code:
    foreach i in "Dep" "Emp" {
    
     import delimited "Q:\DATA\`i'.csv", clear
    
     **converting into panel format
     reshape long a, i(id) j(year)
     rename a `i'
    
     save "Q:\DATA\`i'.dta", replace
    }
    Stata has an issue with the import line. I tried putting in an actual name instead of `i' and Stata has no problem with the save line. I cannot figure out why. Please advice.

  • #2
    I have also tried
    Code:
     "`i'" and also `"`i'"'

    Comment


    • #3
      The problem is the use of the directory separator character \. In Stata (and in many other software programs) the backslash (\) character serves as an "escape" character and gives the following character a special meaning rather than its normal meaning. So when Stata encounters DATA\`i', it does not interpret the \` sequence as a directory separator followed by the opening of a local macro. Instead, it treats \` as a whole to mean a literal ` character, not the opening of a macro, and with no \ before it.

      There are a couple of ways around this. First, you could just run the whole program in the Q:\DATA directory in the first place. Then there would be no need to specify full pathnames anyway. You could just -import delimited `i'.csv-.

      Sometimes there are good reasons to have the data files in a separate directory from where you run the program. So a more robust solution to this problem is to use the forward slash (/) character as the directory separator in the pathnames. Even though Windows expects \, Stata is aware of that makes the change "behind the scenes" when it feeds the pathname to Windows. So all you need to do is run this as:

      Code:
      import delimited "Q:/DATA/`i'.csv", clear
      Don't forget to make the same change in your -save- command.

      In fact, you should really get in the habit of always using the / character as the directory separator in pathnames in Stata. That's mandatory on Mac and Unix installations. And it always works on Windows; so it never hurts, and occasionally avoids obscure problems like this one.

      Comment


      • #4
        This is referred to in the Stata Journal - Nick Cox pointed me to it when I had a similar issue :

        Beware of the backstabbing backslash:

        http://www.stata-journal.com/sjpdf.h...iclenum=pr0042

        Comment


        • #5
          Thanks for explaining directory separator problem in Stata, Clyde I always use Windows so I have never faced these issues. Also, thanks Tim.

          Comment

          Working...
          X