The path/filepath Package
Joining Path Segments
filepath.Join combines multiple path segments into one, correctly using the operating system's path separator and cleaning up redundant slashes -- always preferred over manual string concatenation.
Example: Joining Path Segments
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := filepath.Join("data", "reports", "2024", "summary.csv")
fmt.Println(path)
}
Login to try C/C++/Java/PHP code in the editor
Extracting the Base and Directory
filepath.Base returns just the last element of a path (typically the file name), while filepath.Dir returns everything before it -- useful for splitting a full path into its directory and filename parts.
Example: Extracting the Base and Directory
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := "data/reports/summary.csv"
fmt.Println("base:", filepath.Base(path))
fmt.Println("dir:", filepath.Dir(path))
}
Login to try C/C++/Java/PHP code in the editor
Getting a File Extension
filepath.Ext returns the file extension of a path, including the leading dot, which is handy for branching logic based on file type (like choosing a parser for .csv versus .json).
Example: Getting a File Extension
package main
import (
"fmt"
"path/filepath"
)
func main() {
files := []string{"report.csv", "image.png", "README"}
for _, f := range files {
fmt.Println(f, "->", filepath.Ext(f))
}
}
Login to try C/C++/Java/PHP code in the editor
- Manually joining paths with string concatenation and '/', which breaks on Windows where the separator is '\\'.
- Confusing filepath.Base (the last path element) with filepath.Dir (everything except the last element).
- Assuming filepath.Ext includes the whole file name -- it only returns the extension, starting from the last dot.
- filepath.Join builds a path from parts using the correct OS-specific separator.
- filepath.Base returns the final element of a path; filepath.Dir returns everything before it.
- filepath.Ext returns a file's extension, including the leading dot.
- Using filepath instead of manual string concatenation makes path code portable across operating systems.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: