Go os.MkdirAll
Create a nested directory tree and verify the final directory.
A simple example
os.MkdirAll
- Start with An empty practice folder
- Do this Create a/b including parents
- Result Both directories exist
Syntax
os.MkdirAll(week, 0700)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goPrepare nested hand-in folders
A department creates a hand-in folder for each class and week. The job runs again if the first delivery is interrupted, so existing directories should remain usable on a second run.
package main
import (
"os"
"fmt"
"path/filepath"
)
func check(err error) {
if err != nil { panic(err) }
}
func main() {
dir, err := os.MkdirTemp("", "lesson-")
check(err)
defer os.RemoveAll(dir)
p := func(name string) string { return filepath.Join(dir, name) }
week := p("class/week1")
check(os.MkdirAll(week, 0700))
check(os.MkdirAll(week, 0700))
info, err := os.Stat(week)
check(err)
if info.IsDir() { fmt.Println("ready") }
}
ready
The second attempt finds the same directory and the application can use it.
Locate a rehearsal score
The choir stores each score inside a season folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
Locate a workshop handout
An instructor stores the current template in a class folder. Create the named season or class folder and its proofs subfolder in an empty workspace. What state should the operator see after successful creation?
What to watch for
Handle a regular file occupying any required directory name as an error.