Abs
获取绝对路径
func Abs(path string) (string, error)
pathAbs, _ := filepath.Abs("./")
fmt.Println(pathAbs)
// -> c:\user\...
Rel
返回一个路径的相对路径
func Rel(basepath, targpath string) (string, error)
fmt.Println(filepath.Rel("./file", "../static"))
// -> ../../static 表示从 file指向 static 的相对路径
// 注意;路径内不能包含文件
// 当路径末尾包含文件
fmt.Println(filepath.Rel("./file.js", "../static"))
// -> ../../static 这里将文件作为目录解析
FromSlash
使用 / 替换 为路径分隔符
func FromSlash(path string) string
fmt.Println(filepath.FromSlash("./static.js"))
// -> .\static.js
VolumeName
获取开头卷名
func VolumeName(path string) (v string)
pathAbs, _ := filepath.Abs("./")
fmt.Println(filepath.VolumeName(pathAbs))
// -> C:
Walk
遍历目录树,并执行回调, 类似 map
报错或遍历结束,跳出
func Walk(root string, walkFn WalkFunc) error
var count = 0
func logFileName(path string, info os.FileInfo, err error) error {
count++
// 返回错误后,编辑将终止
if count > 10 {
return errors.New("stop")
}
fmt.Printf("\n %d path: %s fileName: %s", count, path, info.Name())
return nil
}
func main() {
filepath.Walk("./", logFileName)
}
WalkFunc
Walk 回调定义
type WalkFunc func(path string, info os.FileInfo, err error) error
其他
同 path.IsAbs
同 path.Split
同 path.Join
同 path.Dir
同 path.Base
同 path.Ext
同 path.Clean