Skip to content

Go File Paths

Go provides two packages for working with paths: 1. path: For slash-separated paths (like URLs). 2. path/filepath: For operating system paths (Window's \ vs Linux's /). Most of the time, you should use filepath.

1. Joining Paths

Never use manual string concatenation like dir + "/" + file. Use Join to automatically handle separators based on the OS.

package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    p := filepath.Join("dir1", "dir2", "filename.txt")
    fmt.Println(p) 
    // Linux/macOS: dir1/dir2/filename.txt
    // Windows:     dir1\dir2\filename.txt
}

2. Extracting Parts

1
2
3
4
5
6
7
8
p := "/home/user/notes.txt"

fmt.Println(filepath.Dir(p))  // /home/user (Directory)
fmt.Println(filepath.Base(p)) // notes.txt (Filename)
fmt.Println(filepath.Ext(p))  // .txt (Extension)

// Get path without extension
fmt.Println(p[:len(p)-len(filepath.Ext(p))]) // /home/user/notes

3. Absolute vs Relative

1
2
3
4
5
6
// Check if a path is absolute
fmt.Println(filepath.IsAbs("/etc/passwd"))

// Convert a relative path to an absolute one
abs, _ := filepath.Abs("config.json")
fmt.Println(abs)

4. Cleaning Paths

The Clean function removes redundant elements like . (current dir) or .. (parent dir).

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

Why use filepath?

  1. Cross-platform: Your code will work on Windows, Linux, and macOS without changes.
  2. Consistency: It handles trailing slashes and multiple separators (///) correctly.
  3. Security: Cleaning paths helps prevent "Directory Traversal" attacks (like ../../etc/passwd).