← Back to Go Course | Chapter 13: File IO & OS | Lesson 5 of 7

The path/filepath Package

filepath is Go's toolkit for correctly building and taking apart file paths, so your program works the same whether it runs on Windows or Linux.

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

markup
package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	path := filepath.Join("data", "reports", "2024", "summary.csv")
	fmt.Println(path)
}

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

markup
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))
}

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

markup
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))
	}
}
Common Mistakes
  1. Manually joining paths with string concatenation and '/', which breaks on Windows where the separator is '\\'.
  2. Confusing filepath.Base (the last path element) with filepath.Dir (everything except the last element).
  3. Assuming filepath.Ext includes the whole file name -- it only returns the extension, starting from the last dot.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.