获取Golang中给定文件路径的目录名称(不是路径)

问题描述 投票:0回答:1

通过使用带有以下示例的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获取父级的名称?

regex go path directory filepath
1个回答
5
投票

您可以使用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

© www.soinside.com 2019 - 2024. All rights reserved.