Go os.ReadDir
Enumerate immediate directory entries and filter their names by suffix.
A simple example
os.ReadDir
- Start with One folder containing a.txt and b.txt
- Do this List and sort its names
- Result a.txt, b.txt
Syntax
os.ReadDir(dir)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goCount only the invoices in a folder
A market stall saves two CSV invoices and a text note in the same folder. Count just the CSV entries for the daily summary without depending on the order returned by the filesystem.
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) }
for _, name := range []string{"a.csv", "b.csv", "notes.txt"} {
check(os.WriteFile(p(name), nil, 0600))
}
entries, err := os.ReadDir(dir)
check(err)
count := 0
for _, entry := range entries {
if entry.Type().IsRegular() && filepath.Ext(entry.Name()) == ".csv" { count++ }
}
fmt.Println(count)
}
2
The two CSV names pass the filter and the text note is excluded.
Inventory class submissions
A teacher receives two top-level files and one file in a team folder. Count regular files in the top-level folder only. Do not count subfolders as files.
Inventory rehearsal parts
A school stores one score and two parts in a subfolder. Count regular files in the top-level folder only. Do not count subfolders as files.
What to watch for
Directory enumeration order is unspecified. Sort first if the order matters.