Go filepath.Base and Dir
Extract the last component of a path and the name of its parent.
A simple example
filepath.Base and Dir
- Start with Path notes/a.txt
- Do this Read its final component
- Result a.txt
Syntax
filepath.Base(filepath.Dir(receipt))
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goPrint a receipt name and its folder
A school store receives a path from the checkout system. The receipt printer needs just the filename, while the filing clerk needs the name of the folder that holds it.
First output line014.txt
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) }
receipt := p("receipts/014.txt")
fmt.Println(filepath.Base(receipt))
fmt.Println(filepath.Base(filepath.Dir(receipt)))
}
014.txt receipts
The final component is the receipt name. Its parent supplies the filing category.
Advertisements
Locate a rehearsal score
The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.
Givenspring / alto.txt
Worked resultalto.txt
Locate a workshop handout
An instructor stores the current template in a class folder. Build the nested path and read its final name for the screen.
Givenceramics / glaze.pdf
Worked resultglaze.pdf
What to watch for
These are pathname operations. A trailing separator or filesystem root may need separate handling.