HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to create nested directories using Mkdir in Golang?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howdirectoriesusingmkdirgolangnestedcreate

Problem

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.

Solution

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.

Code Snippets

os.MkdirAll(folderPath, os.ModePerm)

Context

Stack Overflow Q#28448543, score: 275

Revisions (0)

No revisions yet.