Working with Directories
Start with Working with Directories
Directory APIs let a program create folders, inspect their entries and build paths that work across operating systems.
What you’ll learn
- Explain the main purpose of working with directories.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
os.MkdirTemp creates a temporary directory, os.ReadDir lists immediate children and filepath.Join forms paths with native separators. Directory entries expose names and basic metadata without requiring a separate stat call for every entry.
ReadDir returns entries sorted by name, while filepath.WalkDir can traverse a whole tree. Avoid constructing trusted paths by blindly concatenating unvalidated user input.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "folders-")
if err != nil {
panic(err)
}
defer os.RemoveAll(dir)
if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("A"), 0600); err != nil {
panic(err)
}
if err := os.WriteFile(filepath.Join(dir, "b.txt"), []byte("B"), 0600); err != nil {
panic(err)
}
entries, err := os.ReadDir(dir)
if err != nil {
panic(err)
}
for _, entry := range entries {
fmt.Println(entry.Name())
}
}
Output
a.txt
b.txtTrace what the program does
Two files are written to a temporary directory. ReadDir returns the directory entries sorted by filename, so the output is a.txt followed by b.txt.
Avoid common mistakes
- Use filepath.Join for filesystem paths rather than hard-coding slashes into platform-dependent layouts.
- os.ReadDir lists one directory; it does not recursively visit all descendants.
Try it yourself
Create an additional subdirectory and print which entries are directories using entry.IsDir().
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Working with Directories in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.