path/filepath

Guided tour · I/O & Files · pkg.go.dev →

OS-aware path manipulation and directory walking. Use this for filesystem paths, not path (which is URL-style).

filepath vs path

filepath uses the OS separator (\ on Windows, / on Unix). The path package always uses / and is for URLs or other slash-separated paths.

Joining, splitting, cleaning

Join — builds a clean path

filepath.Join("a", "b", "c")         // "a/b/c"
filepath.Join("/home", "ada/")       // "/home/ada"
filepath.Join("a", "..", "b")        // "b"

Split, Dir, Base, Ext

dir, file := filepath.Split("/a/b/c.txt") // "/a/b/", "c.txt"
filepath.Dir("/a/b/c.txt")                // "/a/b"
filepath.Base("/a/b/c.txt")               // "c.txt"
filepath.Ext("c.tar.gz")                  // ".gz"

Clean — normalize

filepath.Clean("a//b/../c/")  // "a/c"

Abs and Rel

abs, _ := filepath.Abs("hello.txt")
rel, _ := filepath.Rel("/home/ada", "/home/ada/docs/x.md")
fmt.Println(abs, rel) // ..., "docs/x.md"

Matching and walking

Match — glob against a single path

ok, _ := filepath.Match("*.go", "main.go")     // true
ok, _ = filepath.Match("*.go", "sub/main.go")   // false — * doesn't cross /

Glob — find matching files

matches, _ := filepath.Glob("*.md")
fmt.Println(matches)

WalkDir — recursively visit

Prefer WalkDir over the older Walk — it uses fs.DirEntry and avoids an extra Stat per entry.

filepath.WalkDir(".", func(p string, d fs.DirEntry, err error) error {
    if err != nil { return err }
    if d.IsDir() && d.Name() == "node_modules" {
        return fs.SkipDir
    }
    fmt.Println(p)
    return nil
})