Announcement

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

  • How to capture a folder path in a macro

    Hi everyone,

    I intend to capture a folder path in a macro and use it later in a program to save files to after the end of my DO file. This path shall be capture programmatically through the window command and not manually through the "cd" command

    I found this code helpful but it also include the file name with it. I only need the directory path excluding file name.
    Code:
    capture window fopen D_dta "Select a dataset to use:" xlsx
    1. So, is there a way to either directly capture the directory path
    2. I tried to use the tokenize command to substitute the last token (file name) with white space.
    But, I don't know how to programmatically get the last token instead of manually entering it, and it does not work too.

    Code:
    tokenize "xyz\sample\test\sample.xlsx",p("\")
    global newpath:subinstr global D_dta "`7'" "",all
    di "$newpath"
    Appreciate you help.

  • #2
    There is a series of functions for manipulating file path in Mata. pathutil (SSC) is a wrapper around those functions.

    Code:
    *ssc install pathutil
    pathutil split "xyz\sample\test\sample.xlsx"
    sreturn list
    yields

    Code:
    . pathutil split "xyz\sample\test\sample.xlsx"
    
    . sreturn list
    
    macros:
               s(filename) : "sample"
              s(extension) : ".xlsx"
                 s(suffix) : ".xlsx"
              s(directory) : "xyz\sample\test"

    Comment


    • #3
      Thank you daniel klein. This is what I wanted.
      Appreciate your help

      Comment

      Working...
      X