How to create nested directories using Mkdir in Golang?

前端 未结 5 1229
野趣味
野趣味 2021-01-30 15:33

I am trying to create a set of nested directories from a Go executable such as \'dir1/dir2/dir3\'. I have succeeded in creating a single directory with this line:



        
5条回答
  •  感情败类
    2021-01-30 16:00

    An utility method like the following can be used to solve this.

    import (
      "os"
      "path/filepath"
      "log"
    )
    
    func ensureDir(fileName string) {
      dirName := filepath.Dir(fileName)
      if _, serr := os.Stat(dirName); serr != nil {
        merr := os.MkdirAll(dirName, os.ModePerm)
        if merr != nil {
            panic(merr)
        }
      }
    }
    
    
    
    func main() {
      _, cerr := os.Create("a/b/c/d.txt")
      if cerr != nil {
        log.Fatal("error creating a/b/c", cerr)
      }
      log.Println("created file in a sub-directory.")
    }
    

提交回复
热议问题