【问题标题】:Get the directory name (not a path) of a given file path in Golang获取Golang中给定文件路径的目录名(不是路径)
【发布时间】:2018-05-31 03:57:15
【问题描述】:

通过以下示例使用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.Dirfilepath.Base?

标签: regex go path directory filepath


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-01
    • 2014-04-21
    • 2010-12-14
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-04
    相关资源
    最近更新 更多