Go filepath.WalkDir
Walk a directory tree and select matching regular files.
A simple example
filepath.WalkDir
- Start with Folder a contains b/c.txt
- Do this Visit descendants
- Result The walk reaches c.txt
Syntax
filepath.WalkDir(dir, visit)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goFind a receipt below the month folder
A treasurer has one receipt in a month folder and a note beside that folder. A recursive inventory should locate the nested CSV receipt while leaving the unrelated note out of its total.
package main
import (
"os"
"fmt"
"io/fs"
"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) }
check(os.Mkdir(p("March"), 0700))
check(os.WriteFile(p("March/dues.csv"), nil, 0600))
check(os.WriteFile(p("notes.txt"), nil, 0600))
count := 0
check(filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error {
if err != nil { return err }
if entry.Type().IsRegular() && filepath.Ext(path) == ".csv" { count++ }
return nil
}))
fmt.Println(count)
}
1
The month folder contributes one matching receipt below the top level.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files throughout the folder tree, including its subfolders.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files throughout the folder tree, including its subfolders.
What to watch for
Following symbolic links during recursion can revisit directories. Choose link handling deliberately.