dourong8495
2015-02-11 07:15
浏览 156
已采纳

如何在Golang中使用Mkdir创建嵌套目录?

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:

os.Mkdir("." + string(filepath.Separator) + c.Args().First(),0777);

However, I have no idea how to approach creating a predetermined nested set of directories inside of that directory.

图片转代码服务由CSDN问答提供 功能建议

我正在尝试从Go可执行文件(如“ dir1 / dir2 / dir3”)创建一组嵌套目录。 我已经成功创建以下目录:

  os.Mkdir(“。” + string(filepath.Separator)+ c.Args()。First()  ,0777); 
   
 
 

但是,我不知道如何在该目录内创建预定的嵌套目录集。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • doue1925 2015-02-11 07:25
    已采纳

    os.Mkdir is used to create a single directory. To create a folder path, instead try using:

    os.MkdirAll(folderPath, os.ModePerm)
    

    Go documentation

    func MkdirAll(path string, perm FileMode) error

    MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

    Edit:

    Updated to correctly use os.ModePerm instead.
    For concatenation of file paths, use package path/filepath as described in @Chris' answer.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douqiao1997 2015-02-11 07:26

    If the issue is to create all the necessary parent directories, you could consider using os.MkDirAll()

    MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error.

    The path_test.go is a good illustration on how to use it:

    func TestMkdirAll(t *testing.T) {
        tmpDir := TempDir()
        path := tmpDir + "/_TestMkdirAll_/dir/./dir2"
        err := MkdirAll(path, 0777)
        if err != nil {
        t.Fatalf("MkdirAll %q: %s", path, err)
        }
        defer RemoveAll(tmpDir + "/_TestMkdirAll_")
    ...
    }
    

    (Make sure to specify a sensible permission value, as mentioned in this answer)

    评论
    解决 无用
    打赏 举报
  • dougongnan2167 2015-12-24 10:52

    This way you don't have to use any magic numbers:

    os.MkdirAll(newPath, os.ModePerm)
    

    Also, rather than using + to create paths, you can use:

    import "path/filepath"
    path := filepath.Join(someRootPath, someSubPath)
    

    The above uses the correct separators automatically on each platform for you.

    评论
    解决 无用
    打赏 举报
  • dongxianshuai8927 2019-01-02 04:04

    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.")
    }
    
    评论
    解决 无用
    打赏 举报
  • drogon982007 2019-06-15 04:34

    This is one alternative for achieving the same but it avoids race condition caused by having two distinct "check ..and.. create" operations.

    package main
    
    import (
        "fmt"
        "os"
    )
    
    func main()  {
        if err := ensureDir("/test-dir"); err != nil {
            fmt.Println("Directory creation failed with error: " + err.Error())
            os.Exit(1)
        }
        // Proceed forward
    }
    
    func ensureDir(dirName string) error {
    
        err := os.MkdirAll(dirName, os.ModeDir)
    
        if err == nil || os.IsExist(err) {
            return nil
        } else {
            return err
        }
    }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题