path/filepath

最後更新


path/filepath 處理作業系統的檔案路徑:依平台使用正確的分隔字元組合與拆解路徑,並提供走訪目錄樹、萬用字元搜尋與路徑安全檢查。

這個套件做什麼


Linux 與 macOS 的路徑長這樣:/home/gopher/data/report.csv;Windows 則是 C:\Users\gopher\data\report.csv。如果程式寫死 "data/" + name,換個平台就可能出錯。
filepath 會依目前的作業系統選擇分隔字元(filepath.Separator,Unix 為 /,Windows 為 \),讓同一段程式碼在各平台都產生正確的路徑。
套件分隔字元用在
path永遠是 /URL、fs.FS、embed、zip 內路徑
path/filepath依作業系統交給 os 的磁碟路徑

filepath 大部分函式只做字串運算(Join、Base、Rel、IsLocal);Abs、Glob、WalkDir、EvalSymlinks 則會讀取檔案系統或目前目錄。
本頁輸出在 macOS 上取得,Linux 相同;Windows 上分隔字元會是 \。

匯入


  1. import "path/filepath"

常用 API


filepath.Join、Base、Dir、Ext


和 path 的同名函式相同,但使用作業系統的分隔字元:
  • Join:組合路徑並清理
  • Base:最後一段
  • Dir:所在目錄
  • Ext:副檔名

簽名:
  1. func Join(elem ...string) string
  2. func Base(path string) string
  3. func Dir(path string) string
  4. func Ext(path string) string

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. )
  6. func main() {
  7. p := filepath.Join("data", "2026", "report.csv")
  8. fmt.Println(p)
  9. fmt.Println(filepath.Join("/var/", "log", "..", "tmp"))
  10. fmt.Printf("分隔符號:%q\n", filepath.Separator)
  11. fmt.Println("Base:", filepath.Base(p))
  12. fmt.Println("Dir:", filepath.Dir(p))
  13. fmt.Println("Ext:", filepath.Ext(p))
  14. }

輸出:
  1. data/2026/report.csv
  2. /var/tmp
  3. 分隔符號:'/'
  4. Base: report.csv
  5. Dir: data/2026
  6. Ext: .csv

在 Windows 上,Join("data", "2026", "report.csv") 會得到 data\2026\report.csv。

filepath.Abs


把相對路徑轉成絕對路徑,以目前工作目錄(os.Getwd())為基準。程式啟動時把設定檔路徑轉成絕對路徑,之後就不怕工作目錄改變。
簽名:
  1. func Abs(path string) (string, error)
  2. func IsAbs(path string) bool

範例:工作目錄每台電腦不同,所以只印比較結果。
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. )
  7. func main() {
  8. wd, err := os.Getwd()
  9. if err != nil {
  10. fmt.Println("錯誤:", err)
  11. return
  12. }
  13. abs, err := filepath.Abs("config/app.yaml")
  14. if err != nil {
  15. fmt.Println("錯誤:", err)
  16. return
  17. }
  18. fmt.Println("是絕對路徑:", filepath.IsAbs(abs))
  19. fmt.Println("等於 Getwd + 相對路徑:", abs == filepath.Join(wd, "config/app.yaml"))
  20. fmt.Println(filepath.IsAbs("config/app.yaml"))
  21. }

輸出:
  1. 是絕對路徑: true
  2. 等於 Getwd + 相對路徑: true
  3. false

注意:Abs 不檢查檔案是否存在,也不解析符號連結;需要真實路徑時用 filepath.EvalSymlinks。

filepath.Rel


計算「從 base 走到 target」的相對路徑。常用來把走訪時拿到的完整路徑,轉成相對於專案根目錄的顯示名稱。
簽名:
  1. func Rel(basepath, targpath string) (string, error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. )
  6. func main() {
  7. pairs := [][2]string{
  8. {"/home/gopher/project", "/home/gopher/project/cmd/main.go"},
  9. {"/home/gopher/project", "/home/gopher/notes.txt"},
  10. {"/home/gopher/project", "relative/x"},
  11. }
  12. for _, p := range pairs {
  13. rel, err := filepath.Rel(p[0], p[1])
  14. fmt.Printf("%q %v\n", rel, err)
  15. }
  16. }

輸出:
  1. "cmd/main.go" <nil>
  2. "../notes.txt" <nil>
  3. "" Rel: can't make relative/x relative to /home/gopher/project

注意:一個是絕對路徑、一個是相對路徑時無法計算,會回傳錯誤。

filepath.WalkDir


遞迴走訪磁碟上的目錄樹,每個檔案與目錄呼叫一次回呼函式,依檔名字典序進行。回傳 filepath.SkipDir 跳過目錄,回傳 filepath.SkipAll 停止全部走訪。
它和 fs.WalkDir(見 io/fs)用法相同,差別在 filepath.WalkDir 直接吃磁碟路徑,回呼拿到的路徑包含 root 前綴並使用系統分隔字元。
簽名:
  1. func WalkDir(root string, fn fs.WalkDirFunc) error

範例:找出所有 .go 檔,略過 .git 目錄。
  1. package main
  2. import (
  3. "fmt"
  4. "io/fs"
  5. "os"
  6. "path/filepath"
  7. )
  8. func main() {
  9. root, err := os.MkdirTemp("", "walkdemo")
  10. if err != nil {
  11. fmt.Println("錯誤:", err)
  12. return
  13. }
  14. defer os.RemoveAll(root)
  15. for _, name := range []string{"main.go", "go.mod", "internal/db/db.go", "internal/db/db_test.go", ".git/HEAD"} {
  16. full := filepath.Join(root, name)
  17. os.MkdirAll(filepath.Dir(full), 0o755)
  18. os.WriteFile(full, []byte("x"), 0o644)
  19. }
  20. var goFiles []string
  21. err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
  22. if err != nil {
  23. return err
  24. }
  25. if d.IsDir() && d.Name() == ".git" {
  26. return filepath.SkipDir
  27. }
  28. if !d.IsDir() && filepath.Ext(path) == ".go" {
  29. rel, _ := filepath.Rel(root, path)
  30. goFiles = append(goFiles, rel)
  31. }
  32. return nil
  33. })
  34. fmt.Println(goFiles, err)
  35. }

輸出:
  1. [internal/db/db.go internal/db/db_test.go main.go] <nil>

注意:WalkDir 不會跟隨符號連結進入目錄。舊版的 filepath.Walk 每個項目都會呼叫 Lstat,速度較慢,新程式用 WalkDir。

filepath.Glob 與 filepath.Match


Glob 在磁碟上找出符合萬用字元樣式的檔案,回傳排序後的完整路徑;Match 只比對字串,不碰磁碟。樣式語法與 path 的 Match 相同(*、?、[...])。
簽名:
  1. func Glob(pattern string) (matches []string, err error)
  2. func Match(pattern, name string) (matched bool, err error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. )
  7. func main() {
  8. dir, err := os.MkdirTemp("", "globdemo")
  9. if err != nil {
  10. fmt.Println("錯誤:", err)
  11. return
  12. }
  13. defer os.RemoveAll(dir)
  14. for _, name := range []string{"a.log", "b.log", "c.txt", "2026-01.log"} {
  15. os.WriteFile(filepath.Join(dir, name), nil, 0o644)
  16. }
  17. matches, err := filepath.Glob(filepath.Join(dir, "*.log"))
  18. if err != nil {
  19. fmt.Println("錯誤:", err)
  20. return
  21. }
  22. for _, m := range matches {
  23. fmt.Println(filepath.Base(m))
  24. }
  25. ok, _ := filepath.Match("2026-??.log", "2026-01.log")
  26. fmt.Println("Match:", ok)
  27. }

輸出:
  1. 2026-01.log
  2. a.log
  3. b.log
  4. Match: true

注意:Glob 會忽略讀取目錄時的 I/O 錯誤,只在樣式寫錯時回傳 ErrBadPattern;它也不支援 ** 遞迴比對,需要遞迴時用 WalkDir。

filepath.IsLocal 與 filepath.Localize


處理外部傳入的檔名時,要確認它不會跑出指定目錄:
  • IsLocal(path)(Go 1.20 起):只做字串檢查,路徑是相對路徑、不為空、清理後不會用 .. 跑出目前目錄時回傳 true;在 Windows 上也會拒絕 NUL 這類保留名稱
  • Localize(path)(Go 1.23 起):把 / 分隔的 fs.FS 風格路徑轉成作業系統路徑,路徑不合法時回傳錯誤

簽名:
  1. func IsLocal(path string) bool
  2. func Localize(path string) (string, error)

範例:
  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. )
  6. func main() {
  7. for _, p := range []string{"avatar.png", "user/1/avatar.png", "../etc/passwd", "/etc/passwd", "a/../../b", ""} {
  8. fmt.Printf("%-20q IsLocal=%v\n", p, filepath.IsLocal(p))
  9. }
  10. local, err := filepath.Localize("uploads/2026/a.png")
  11. fmt.Println(local, err)
  12. _, err = filepath.Localize("../a.png")
  13. fmt.Println(err)
  14. }

輸出:
  1. "avatar.png" IsLocal=true
  2. "user/1/avatar.png" IsLocal=true
  3. "../etc/passwd" IsLocal=false
  4. "/etc/passwd" IsLocal=false
  5. "a/../../b" IsLocal=false
  6. "" IsLocal=false
  7. uploads/2026/a.png <nil>
  8. invalid path

注意:IsLocal 只看字串,不會發現指向外部的符號連結。真正要限制檔案存取範圍時,用 os.OpenRoot(Go 1.24 起,見 os)。

filepath.ToSlash、FromSlash 與 SplitList


  • ToSlash:把系統分隔字元換成 /,用於把磁碟路徑轉成 URL 或寫進設定檔
  • FromSlash:把 / 換成系統分隔字元
  • SplitList:切開 PATH 這類以清單分隔字元(Unix 為 :,Windows 為 ;)組成的字串
  • Clean:與 path.Clean 規則相同,使用系統分隔字元

簽名:
  1. func ToSlash(path string) string
  2. func FromSlash(path string) string
  3. func SplitList(path string) []string
  4. func Clean(path string) string

範例:在 Unix 上分隔字元本來就是 /,所以 ToSlash/FromSlash 不改變內容;在 Windows 上 FromSlash 會得到 assets\img\logo.png。
  1. package main
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. )
  6. func main() {
  7. urlPath := "assets/img/logo.png"
  8. osPath := filepath.FromSlash(urlPath)
  9. fmt.Println("FromSlash:", osPath)
  10. fmt.Println("ToSlash:", filepath.ToSlash(osPath))
  11. fmt.Println(filepath.SplitList("/usr/local/bin:/usr/bin:/bin"))
  12. fmt.Println(filepath.Clean("./a//b/../c/"))
  13. }

輸出:
  1. FromSlash: assets/img/logo.png
  2. ToSlash: assets/img/logo.png
  3. [/usr/local/bin /usr/bin /bin]
  4. a/c

重點整理


  • 磁碟路徑用 filepath,URL 與 fs.FS 路徑用 path
  • 組合路徑一律用 filepath.Join,不要用字串相加與寫死的 /
  • Rel 搭配 WalkDir 可以得到相對於根目錄的路徑;遞迴走訪用 WalkDir 而不是 Walk
  • Glob 不支援 **,也會忽略 I/O 錯誤
  • IsLocal 只是字串檢查;真正限制存取範圍用 os.OpenRoot

資料來源