How to create nested directories using Mkdir in Golang?

前端 未结 5 1230
野趣味
野趣味 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-30 16:03

    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)

提交回复
热议问题