Go📦Standard Libraryintermediate
path/filepath — File Paths
Go · Standard Library · Run with go run
Explanation
The `path/filepath` package manipulates file paths using the operating system's separator (`/` on Unix, `\` on Windows) — making path code portable. `filepath.Join` builds paths safely, `filepath.Base`/`Dir`/`Ext` split them apart, and `filepath.Walk`/`WalkDir` traverse directory trees. Use `path` (not `filepath`) only for URL-style slash paths.
Real-World Scenario
A build tool must find every `.go` file under a project directory, on both developer macOS laptops and Linux CI runners. `filepath.WalkDir` recursively visits each entry, and `filepath.Ext` filters by extension — identical behavior on every OS.
Quick Snippet
snippet.go
import "path/filepath"
p := filepath.Join("data", "logs", "app.log")
// "data/logs/app.log" on Unix, "data\logs\app.log" on Windows
filepath.Base(p) // "app.log"
filepath.Dir(p) // "data/logs"
filepath.Ext(p) // ".log"
// Walk a directory tree
filepath.WalkDir("src", func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() && filepath.Ext(path) == ".go" {
fmt.Println(path)
}
return nil
})Full Example
filepath_pkg.go
// Compile: go run filepath_pkg.go
// Output (separators are OS-specific):
// joined: data/logs/app.log
// base: app.log
// dir: data/logs
// ext: .log
// cleaned: a/c
package main
import (
"fmt"
"path/filepath"
)
func main() {
p := filepath.Join("data", "logs", "app.log")
fmt.Println("joined:", filepath.ToSlash(p))
fmt.Println("base:", filepath.Base(p))
fmt.Println("dir: ", filepath.ToSlash(filepath.Dir(p)))
fmt.Println("ext: ", filepath.Ext(p))
// Clean resolves . and .. segments
fmt.Println("cleaned:", filepath.ToSlash(filepath.Clean("a/b/../c")))
}
Run command
go run filepath_pkg.go