File paths and directories
- Version
- 1.27
- Review
- Draft
Summary#
path/filepath builds and examines paths with the operating system's separator. os.MkdirAll creates missing parents, os.ReadDir lists one directory, and filepath.WalkDir visits a whole tree in lexical order.
Syntax#
path := filepath.Join(root, "docs", name)
err := os.MkdirAll(path, 0o755)
entries, err := os.ReadDir(path)
err = filepath.WalkDir(root, visit)
Example#
package main
import (
"fmt"
"io/fs"
"os"
"path/filepath"
)
func run() error {
root, err := os.MkdirTemp("", "site-*")
if err != nil {
return err
}
defer os.RemoveAll(root)
for _, name := range []string{"main.go", "docs/guide.md", "docs/img/logo.svg"} {
path := filepath.Join(root, filepath.FromSlash(name))
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return err
}
if err := os.WriteFile(path, nil, 0o644); err != nil {
return err
}
}
entries, err := os.ReadDir(root) // sorted by name
if err != nil {
return err
}
for _, entry := range entries {
fmt.Println(entry.Name(), "directory:", entry.IsDir())
}
return filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
if entry.Name() == "img" {
return filepath.SkipDir
}
return nil
}
relative, err := filepath.Rel(root, path)
if err != nil {
return err
}
fmt.Println("file:", filepath.ToSlash(relative), filepath.Ext(path))
return nil
})
}
func main() {
if err := run(); err != nil {
fmt.Println(err)
}
}
Expected output#
docs directory: true
main.go directory: false
file: docs/guide.md .md
file: main.go .go
Common mistakes#
Handle the callback's err argument before using the entry. Joining a path containing .. can produce a path outside the starting directory. Validate untrusted relative paths with a check such as filepath.IsLocal, which checks the text only. A symbolic link can still point outside the starting directory.
Version applicability#
Join, Ext, Rel and os.MkdirAll work from Go 1.0. The 0o permission literals require Go 1.13. The complete example requires Go 1.16 for os.ReadDir, filepath.WalkDir, io/fs and the temporary-file setup. Earlier versions use ioutil.ReadDir and filepath.Walk. filepath.IsLocal requires Go 1.20 or later.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0