Golang filepath包常用方法介绍

本文介绍与文件路径相关包,该工具包位于path/filepath中,该包试图与目标操作系统定义的文件路径兼容。本文介绍一些常用函数,如获取文件绝对路径,获取文件名或目录名、遍历文件、分割文件路径、文件名模式匹配等函数,并给具体示例进行说明。

绝对路径

绝对路径时从根目录开始的完整路径,相对路径是相对与当前工作目录的路径。filepath.Abs 返回文件的绝对路径,filepath.IsAbs 可以检查给定路径是否为绝对路径。请看示例:

package main

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    fname := "./main.go"
    abs_fname, err := filepath.Abs(fname)

    if err != nil {
        log.Fatal(err)
    }

    if filepath.IsAbs(fname) {
        fmt.Printf("%s - is an absolute path\n", fname)
    } else {
        fmt.Printf("%s - is not an absolute path\n", fname)
    }

    if filepath.IsAbs(abs_fname) {
        fmt.Printf("%s - is an absolute path\n", abs_fname)
    } else {
        fmt.Printf("%s - is not an absolute path\n", abs_fname)
    }
}

上述示例使用了filepath.Abs 和 filepath.IsAbs 函数,分别获取绝对路径并判断给定文件路径是否为绝对路径。

文件名和目录

filepath.Base函数返回文件路径的最后元素,通常为文件名。filepath.Dir返回文件路径中除了最后元素的部分,通常为文件目录。

package main

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {

    p, err := filepath.Abs("./main.go")

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(p)

    fmt.Printf("Base: %s\n", filepath.Base(p))
    fmt.Printf("Dir: %s\n", filepath.Dir(p))
}

运行程序分别打印出文件名和文件所在目录。

filepath.Ext

filepath.Ext返回文件路径中文件的扩展名。

package main

import (
    "fmt"
    "path/filepath"
)

func main() {

    p := "/home/user7/media/aliens.mp4"
    ext := filepath.Ext(p)
    fmt.Println("File extension:", ext)

    p = "./main.go"
    ext = filepath.Ext(p)
    fmt.Println("File extension:", ext)
}

运行程序,分别返回mp4和go扩展名。

最短路径

filepath.Clean函数清除重复和不规则的文件路径,通过纯词法处理返回与指定路径等效的最短路径名。

package main

import (
    "fmt"
    "path"
)

func main() {

    paths := []string{
        "home/user7",
        "home//user7",
        "home/user7/.",
        "home/user7/Documents/..",
        "/../home/user7",
        "/../home/Documents/../././/user7",
        "",
    }

    for _, p := range paths {
        fmt.Printf("%q = %q\n", p, path.Clean(p))
    }
}

运行程序输出结果为:

$ go run main.go
"home/user7" = "home/user7"
"home//user7" = "home/user7"
"home/user7/." = "home/user7"
"home/user7/Documents/.." = "home/user7"
"/../home/user7" = "/home/user7"
"/../home/Documents/../././/user7" = "/home/user7"
"" = "."

路径分割

filepath.Split函数分割给定路径为目录和文件组件,filepath.SplitList函数分割一组由OS指定分隔符的连接字符串生成字符串切片。

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {

    cwd, err := os.Getwd()

    if err != nil {
        log.Fatal(err)
    }

    dir, file := filepath.Split(cwd)

    fmt.Printf("Directory: %s\n", dir)
    fmt.Printf("File: %s\n", file)

    home, err := os.UserHomeDir()

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("-------------------------")

    dir, file = filepath.Split(home)

    fmt.Printf("Directory: %s\n", dir)
    fmt.Printf("File: %s\n", file)

    path_env := os.Getenv("PATH")
    paths := filepath.SplitList(path_env)

    for _, p := range paths {
        fmt.Println(p)
    }
}

上例中首先分割当前工作目录和用户主目录,然后把path变量的一组路径分割为切片。

文件遍历

filepath.Walk函数在根目录下遍历文件树。函数签名为:

func Walk(root string, fn WalkFunc) error

遍历目录树下每个文件或目录,包括root目录。

package main

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {

    var files []string

    root := "/home/jano/Documents"

    err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {

        if err != nil {
            fmt.Println(err)
            return nil
        }

        if !info.IsDir() && filepath.Ext(path) == ".txt" {
            files = append(files, path)
        }
        return nil
    })

    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {
        fmt.Println(file)
    }
}

上面示例遍历Document目录下文件,列举所有文本文件(扩展名为txt的文件)。

文件名匹配

filepath.Glob函数返回模式匹配的文件名,不匹配则返回nil。函数签名如下:

func Glob(pattern string) (matches []string, err error)

请下面示例代码:

package main

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    files, err := filepath.Glob("/home/jano/Documents/prog/go/**/**/*.go")

    fmt.Println(len(files))

    if err != nil {
        log.Fatal(err)
    }

    for _, file := range files {

        fmt.Println(file)
    }
}

上面示例列举给定目录下所有go文件,**模式表示递归列举。其他模式格式为:

pattern:
	{ term }
term:
	'*'         matches any sequence of non-Separator characters
	'?'         matches any single non-Separator character
	'[' [ '^' ] { character-range } ']'
	            character class (must be non-empty)
	c           matches character c (c != '*', '?', '\\', '[')
	'\\' c      matches character c

character-range:
	c           matches character c (c != '\\', '-', ']')
	'\\' c      matches character c
	lo '-' hi   matches character c for lo <= c <= hi

filepath.VolumeName

filepath.VolumeName函数基于文件路径返回windows前导卷名称,其他平台返回空字符串。举例:给定"C:\foo\bar" 在 Windows平台返回 “C:”。 给定 “\host\share\foo” 返回 “\host\share”。其他平台返回 “”。

请看示例:

package main

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    fname := "./main.go"
    ap, err := filepath.Abs(fname)

    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(filepath.VolumeName(ap))
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值