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)) } 

到此这篇关于Golang filepath包常用函数详解的文章就介绍到这了,更多相关Go filepath内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是Golang filepath包常用函数详解的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程