通过使用带有以下示例的path/filepath
包,您可以从文件路径获取完整目录路径。
package main
import (
"fmt"
"path/filepath"
)
func main() {
// Output: /path/to/dir
fmt.Println(filepath.Dir("/path//to/dir/file.ext"))
}
但是有没有Parent
函数从路径获得dir
? (这是文件目录的名称):
// The `Parent` is what I want,
// and this is a pseudo-code example, this won't actually work.
//
// Output: dir
fmt.Println(filepath.Parent("/path//to/dir/file.ext"))
如果无法使用函数完成,如何使用RegExp获取父级的名称?
您可以使用filepath.Base
获取目录的最后一个元素。例如:
package main
import (
"fmt"
"path/filepath"
)
func main() {
paths := []string{
"/home/arnie/amelia.jpg",
"/mnt/photos/",
"rabbit.jpg",
"/usr/local//go",
}
for _, p := range paths {
dir := filepath.Dir(p)
parent := filepath.Base(dir)
fmt.Printf("input: %q\n\tdir: %q\n\tparent: %q\n", p, dir, parent)
}
}
返回:
input: "/home/arnie/amelia.jpg"
dir: "/home/arnie"
parent: "arnie"
input: "/mnt/photos/"
dir: "/mnt/photos"
parent: "photos"
input: "rabbit.jpg"
dir: "."
parent: "."
input: "/usr/local//go"
dir: "/usr/local"
parent: "local"
(例子改编自filepath examples)