How to create nested directories using Mkdir in Golang?

前端 未结 5 1223
野趣味
野趣味 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:11

    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.

提交回复
热议问题