Go by Example

Directories

Create nested directories, list entries, remove directory trees, and traverse recursively with error handling.

The os package creates, lists and removes directories, which are folders that hold files or other folders. MkdirAll creates a directory and any missing parent folders. ReadDir lists the entries in a directory by name.

Each DirEntry represents one item in the folder. It provides the item's name and lets the program check whether it is another directory.

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 inside it without asking. Check the path before using it. Avoid Chdir in a server because it changes the current folder for the whole program. Use filepath.WalkDir to visit every item in a directory tree.

Enjoyed this? Get more software craft delivered to your inbox.