Directories
Create nested directories, list entries, remove directory trees, and traverse recursively with error handling.
The os package creates, lists, and removes directories. MkdirAll creates missing parent directories; ReadDir lists entries in name order.
Each returned DirEntry provides a name and an IsDir check without reading full file metadata.
package main
import (
"fmt"
"os"
)
func main() {
if err := os.MkdirAll("reports/2026", 0755); err != nil {
panic(err)
}
entries, err := os.ReadDir("reports")
if err != nil {
panic(err)
}
for _, entry := range entries {
fmt.Println(entry.Name(), entry.IsDir())
}
}In production
RemoveAll deletes a path and everything below it without confirmation; validate the target before using it. Avoid Chdir in servers because it changes the working directory for the whole process. Use filepath.WalkDir when a recursive traversal needs consistent error handling.
Enjoyed this? Get more software craft delivered to your inbox.