path/filepath

path/filepath Join, Clean, Rel, and WalkDir, with separators as measured on darwin rather than invented Windows paths.

模块页正文目前为英文。

The path/filepath package manipulates file-system paths using the separator of the target operating system. Import it as "path/filepath". The path package, by contrast, always uses forward slashes and is the better fit for URLs and other slash-separated names that should not change with GOOS.

The examples on this page were run with Go 1.24.0 on darwin/arm64, where filepath.Separator is '/'. They do not invent Windows backslash output. On Windows, the official documentation states that Separator is '\\', ToSlash replaces that separator with '/', IsAbs recognizes drive letters and UNC paths, and Match treats '\\' as a separator instead of an escape.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
filepath.Join, filepath.Split, filepath.Base, filepath.Dir, filepath.Ext, filepath.CleanBuild, split, and lexically clean operating-system paths. On this darwin host the separator is a slash.
filepath.IsAbs, filepath.Rel, filepath.ToSlash, filepath.FromSlashTest absolute paths, compute a relative path, or convert separators. Results depend on GOOS and are measured here on darwin.
filepath.Match, filepath.WalkDirMatch a shell-style file-name pattern, or walk a directory tree in lexical order without following symlinks.

Join, Split, Base, Dir, Ext, and Clean

Join inserts the OS separator between elements, ignores empty elements, and then runs Clean. A later element that starts with a slash is not treated as a new root on Unix: Join("a", "/b") is a/b on this host, not /b. Split cuts immediately after the final separator and satisfies path == dir+file. Base is the last element, Dir is everything before it after Clean, and Ext is the suffix starting at the final dot of the final element. Clean is purely lexical: it collapses separators, "." , and ".." .

filepath.Join, filepath.Split, filepath.Base, filepath.Dir, filepath.Ext, filepath.Clean

func Join(elem ...string) string
func Split(path string) (dir, file string)
func Base(path string) string
func Dir(path string) string
func Ext(path string) string
func Clean(path string) string

Build, split, and lexically clean operating-system paths. On this darwin host the separator is a slash.

ParameterDescription
elemPath elements to join. Empty elements are ignored. If every element is empty, Join returns the empty string.
pathThe path to split, inspect, or clean.

Returns: Join, Base, Dir, Ext, and Clean return strings. Split returns dir and file such that path == dir+file.

  • These outputs were measured on darwin/arm64. Do not treat them as Windows results.
  • Base of an empty path is ".", and Dir of an empty path is ".". Ext is empty when the final element has no dot.
go
package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	fmt.Printf("separator=%q\n", string(filepath.Separator))
	fmt.Println(filepath.Join("home", "ada", "src.go"))
	fmt.Println(filepath.Join("a", "/b"))
	fmt.Println(filepath.Join("a", "", "b"))
	dir, file := filepath.Split("home/ada/src.go")
	fmt.Printf("%q %q\n", dir, file)
	fmt.Println(filepath.Base("home/ada/src.go"))
	fmt.Println(filepath.Dir("home/ada/src.go"))
	fmt.Println(filepath.Ext("src.go"))
	fmt.Println(filepath.Clean("a/b/../c//./d"))
}

Expected output

separator="/"
home/ada/src.go
a/b
a/b
"home/ada/" "src.go"
src.go
home/ada
.go
a/c/d

Official documentation →

IsAbs, Rel, slashes, Match, and WalkDir

IsAbs reports whether a path is absolute in the sense of this operating system. On this darwin host, "/tmp/x" is absolute and both "tmp/x" and the Windows-looking string "C:\\tmp\\x" are not. Rel returns a lexical relative path; it does not consult the working directory unless it has to, and it returns an error when a relative path cannot be computed. ToSlash replaces each OS separator with '/'; FromSlash does the reverse. Because the separator here is already '/', ToSlash leaves a backslash in the string unchanged, and FromSlash leaves "a/b" unchanged. Those two calls are not a way to invent Windows paths on macOS.

Match requires the pattern to match the whole name. "*" does not cross a separator, so "*.go" matches "main.go" and does not match "src/main.go". WalkDir walks in lexical order, does not follow symbolic links, and yields paths that use the OS separator. The example below walks a temporary directory and prints paths relative to that root so the random parent directory is never printed.

filepath.IsAbs, filepath.Rel, filepath.ToSlash, filepath.FromSlash

func IsAbs(path string) bool
func Rel(basepath, targpath string) (string, error)
func ToSlash(path string) string
func FromSlash(path string) string

Test absolute paths, compute a relative path, or convert separators. Results depend on GOOS and are measured here on darwin.

ParameterDescription
pathThe path to inspect or convert.
basepath, targpathRel returns a path that is lexically equivalent to joining basepath with the result.

Returns: IsAbs returns whether the path is absolute on this OS. Rel returns the relative path and an error if it cannot be computed. ToSlash and FromSlash return converted strings.

Errors

  • error — Rel returns an error when targpath cannot be made relative to basepath, or when the current working directory would be required to compute it.
  • On this host IsAbs("C:\\tmp\\x") is false. A Windows measurement is not shown here.
  • ToSlash("a\\b") printed as %q is "a\\b" on darwin, because "\\" is not the separator.
go
package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	fmt.Println(filepath.IsAbs("/tmp/x"), filepath.IsAbs("tmp/x"), filepath.IsAbs("C:\\tmp\\x"))
	rel, err := filepath.Rel("home/ada", "home/ada/src/main.go")
	fmt.Printf("%q %v\n", rel, err)
	fmt.Printf("%q %q\n", filepath.ToSlash("a\\b"), filepath.FromSlash("a/b"))
}

Expected output

true false false
"src/main.go" <nil>
"a\\b" "a/b"

Official documentation →

filepath.Match, filepath.WalkDir

func Match(pattern, name string) (matched bool, err error)
func WalkDir(root string, fn fs.WalkDirFunc) error

Match a shell-style file-name pattern, or walk a directory tree in lexical order without following symlinks.

ParameterDescription
pattern, nameMatch reports whether name matches pattern in full. "*" and "?" do not match a separator.
root, fnWalkDir calls fn for each file and directory, including root. The paths use the OS separator.

Returns: Match returns whether the name matched and an error only when the pattern is malformed (ErrBadPattern). WalkDir returns the first error that fn does not filter out.

Errors

  • filepath.ErrBadPattern — The only error Match itself returns, when the pattern is malformed.
  • On Windows, official documentation says escaping in Match is disabled and "\\" is a separator. That behavior is not measured on this host.
  • WalkDir is deterministic because it reads a directory and walks names in lexical order. The example uses os.MkdirTemp and prints filepath.Rel paths only.
go
package main

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

func main() {
	ok, err := filepath.Match("*.go", "main.go")
	fmt.Println(ok, err)
	ok, err = filepath.Match("*.go", "src/main.go")
	fmt.Println(ok, err)

	root, err := os.MkdirTemp("", "filepath-ref-")
	if err != nil {
		fmt.Println(err)
		return
	}
	defer os.RemoveAll(root)
	_ = os.Mkdir(filepath.Join(root, "a"), 0o755)
	_ = os.WriteFile(filepath.Join(root, "b.txt"), []byte("b"), 0o644)
	_ = os.WriteFile(filepath.Join(root, "a", "c.txt"), []byte("c"), 0o644)
	err = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		rel, relErr := filepath.Rel(root, p)
		if relErr != nil {
			return relErr
		}
		fmt.Printf("%s dir=%v\n", rel, d.IsDir())
		return nil
	})
	fmt.Println(err)
}

Expected output

true <nil>
false <nil>
. dir=true
a dir=true
a/c.txt dir=false
b.txt dir=false
<nil>

Official documentation →