在 Golang 中获取给定文件路径的目录名(不是路径)
Get the directory name (not a path) of a given file path in Golang
通过使用带有以下示例的 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 获取 parent 的名称?
您可以使用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)
}
}
Returns:
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)
通过使用带有以下示例的 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 获取 parent 的名称?
您可以使用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)
}
}
Returns:
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)