通过将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示例)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句