Announcement

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

  • test whether a directory exists

    Hello All,
    I want to test whether a directory exists. I'm using Stata 13 under Windows.
    I know that there is a -confirm file- command, but not -confirm directory-.

    Supposing the directory name is temp, I can do
    dir temp\
    or
    dir temp

    and I'll see either some files listed, or
    file not found

    but the latter is not an error; it is just information. Under -capture-, _rc yields 0.

    Another possibility is to issue a dir command in the command prompt, using ! or -shell-. But how would I get information from that action back into Stata?
    (I've thought of doing -dir temp\ >xyz.txt- , and then trying to read xyz.txt within Stata. Or maybe the solution would be a plugin. Either of those options seem like a long way to go for such a simple goal.)

    I should state my purpose. I have a facility for moving data files into a directory, that I invoke prior to running a do-file which saves data files. The purpose is so that, on a repeat run, the prior generation of the saved file is kept in a temp\ directory -- rather than overwritten -- so I can compare and see what's changed. I want to invoke this in an automated way, but need to be sure that the desired directory (temp\) exists. Otherwise, the (Windows command prompt) move command will fail.

    Thanks if anyone can help.

    P.S., as I write this, it occurred to me that I can issue
    !md temp\
    which will create the directory if necessary, or do nothing if it already exists as a directory.
    So that may be the simplest option. But with that, I'd prefer to be able to tell whether that command succeeded; it could fail if a file (not a directory) of that name exists.
    (So I suppose I could precede that by testing -confirm file temp-.)

    Again, as I write, I may have found a solution, but I'll appreciate if anyone has some further insight.
    Thanks again.
    --David

  • #2
    Mata has a direxists() function. There is also confirmdir from SSC.

    Best
    Daniel

    Comment


    • #3
      I just got confirmdir from SSC. This is exactly what I needed (and it is remarkably simple code as well). Thanks to Daniel Klein, and to Dan Blanchette for writing it.
      --David

      Comment


      • #4
        I also threw something together quickly that I use to build the directory if it doesn't exist: https://github.com/wbuchanan/dirfile

        Comment


        • #5
          To add to this I'd recommend Scott Long's Stata Pess book, Workflow for Data Analysis. In the book's website, he includes batch files to generate workflow directories.
          Nathan E. Fosse, PhD
          [email protected]

          Comment

          Working...
          X