import “path/filepath”
作用:
Package filepath implements utility routines for manipulating filename paths in a way compatible with the target operating system-defined file paths.

常量

const (

    Separator     = os.PathSeparator
    ListSeparator = os.PathListSeparator

)

ToSlash

func ToSlash(path string) string
1
ToSlash returns the result of replacing each separator character in path with a slash (‘/’) character. Multiple separators are replaced by multiple slashes.
将 path 中平台相关的路径分隔符转换为 ‘/’

FromSlash

func FromSlash(path string) string

FromSlash returns the result of replacing each slash (‘/’) character in path with a separator character. Multiple slashes are replaced by multiple separators.
将 path 中的 ‘/’ 转换为系统相关的路径分隔符

应用:

package main

import (
   "fmt"
   "net/url"
   "os"
   "path/filepath"
)

func main() {
    s := "https://www.wangshubo.com/a/b/c/d"
    u, _ := url.Parse(s)
    s = u.Path

    s = filepath.FromSlash(s)
    fmt.Println(s)
    
    if err := os.MkdirAll(s[1:], 0777); err != nil {
        fmt.Println(err)
    }
    
    s = filepath.ToSlash(s)
    fmt.Println(s)

}

输出:
abcd
/a/b/c/d

Dir

func Dir(path string) string

Dir returns all but the last element of path, typically the path’s directory.
获取 path 中最后一个分隔符之前的部分(不包含分隔符)

Base

func Base(path string) string

Base returns the last element of path. Trailing path separators are removed before extracting the last element. If the path is empty, Base returns “.”. If the path consists entirely of separators, Base returns a single separator.
获取 path 中最后一个分隔符之后的部分(不包含分隔符)

// 获取 path 中最后一个分隔符前后的两部分,之前包含分隔符,之后不包含分隔符
Split(path string) (dir, file string)

// 获取路径字符串中的文件扩展名
Ext(path string) string

应用:

package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    path := `a///b///c///d`
    path = filepath.FromSlash(path)

    d1 := filepath.Dir(path)
    fmt.Println(d1)
    f1 := filepath.Base(path)
    fmt.Println(f1)
    
    d2, f2 := filepath.Split(path)
    fmt.Println(d2)
    fmt.Println(f2)
    
    ext := filepath.Ext(path)
    fmt.Println(ext)

}

输出:
abc
d
a\b\c\
d

func Rel

func Rel(basepath, targpath string) (string, error)

Rel returns a relative path that is lexically equivalent to targpath when joined to basepath with an intervening separator. That is, Join(basepath, Rel(basepath, targpath)) is equivalent to targpath itself. On success, the returned path will always be relative to basepath, even if basepath and targpath share no elements. An error is returned if targpath can’t be made relative to basepath or if knowing the current working directory would be necessary to compute it. Rel calls Clean on the result.
// 获取 targpath 相对于 basepath 的路径。
// 要求 targpath 和 basepath 必须“都是相对路径”或“都是绝对路径”。
Rel(basepath, targpath string) (string, error)

应用:

package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    s, err := filepath.Rel(`/a/b/c`, `/a/b/c/d/e`)
    fmt.Println(s, err)

    s, err = filepath.Rel(`a/b/c`, `a/b/c/d/e`)
    fmt.Println(s, err)
    
    s, err = filepath.Rel(`/a/b/c`, `a/b/c/d/e`)
    fmt.Println(s, err)
    
    s, err = filepath.Rel(`a/b/c`, `/a/b/c/d/e`)
    fmt.Println(s, err)
    
    s, err = filepath.Rel(`a/b/c`, `a/b/d/e`)
    fmt.Println(s, err)

}

输出:
de < nil>
de < nil>
Rel: can’t make a/b/c/d/e relative to /a/b/c
Rel: can’t make /a/b/c/d/e relative to a/b/c
..de < nil>

func Join

func Join(elem ...string) string

Join joins any number of path elements into a single path, adding a Separator if necessary. Join calls Clean on the result; in particular, all empty strings are ignored. On Windows, the result is a UNC path if and only if the first path element is a UNC path.

将 elem 中的多个元素合并为一个路径,忽略空元素,清理多余字符。
应用:

package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    fmt.Println("On Windows:")
    fmt.Println(filepath.Join("a", "b", "c"))
    fmt.Println(filepath.Join("a", "b/c"))
    fmt.Println(filepath.Join("a/b", "c"))
    fmt.Println(filepath.Join("a/b", "/c"))
}

输出:
On Windows:
abc
abc
abc
abc

func Abs

func Abs(path string) (string, error)

Abs returns an absolute representation of path. If the path is not absolute it will be joined with the current working directory to turn it into an absolute path. The absolute path name for a given file is not guaranteed to be unique. Abs calls Clean on the result.
获取 path 的绝对路径

IsAbs
判断路径是否为绝对路径

应用:

package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    s1 := `a/b/c/d`
    fmt.Println(filepath.Abs(s1)) // 不同系统显示不一样
    s2 := `D:\go_workspace\src\go_file_path\a\b\c\d`
    fmt.Println(filepath.IsAbs(s1)) // false
    fmt.Println(filepath.IsAbs(s2)) // true
}

输出:
D:go_workspacesrcgo_file_pathabcd
false
true

Match(pattern, name string) (matched bool, err error)
// 判断 name 是否和指定的模式 pattern 完全匹配

// pattern 规则如下:
// 可以使用 ? 匹配单个任意字符(不匹配路径分隔符)。
// 可以使用 * 匹配 0 个或多个任意字符(不匹配路径分隔符)。
// 可以使用 [] 匹配范围内的任意一个字符(可以包含路径分隔符)。
// 可以使用 [^] 匹配范围外的任意一个字符(无需包含路径分隔符)。
// [] 之内可以使用 - 表示一个区间,比如 [a-z] 表示 a-z 之间的任意一个字符。
// 反斜线用来匹配实际的字符,比如 匹配 ,[ 匹配 [,a 匹配 a 等等。
// [] 之内可以直接使用 [ * ?,但不能直接使用 ] -,需要用 ]、- 进行转义。

应用:

package main

 import (
         "fmt"
         "path/filepath"
 )

 func main() {

         filename := "start.txt"
    
         pattern := "*art*"
    
         matched, err := filepath.Match(pattern, filename)
    
         if err != nil {
                 fmt.Println(err)
         }
    
         fmt.Println(matched)
    
         //---------------------------------
    
         pattern = "*fart*"
    
         matched, err = filepath.Match(pattern, filename)
    
         if err != nil {
                 fmt.Println(err)
         }
    
         fmt.Println(matched)
    
         //---------------------------------
    
         filename = "data123.csv"
    
         pattern = "data[0-9]*"
    
         matched, err = filepath.Match(pattern, filename)
    
         if err != nil {
                 fmt.Println(err)
         }
    
         fmt.Println(matched)

 }

输出:
true
false
true

Walk(root string, walkFn WalkFunc) error
// 遍历指定目录(包括子目录),对遍历到的项目用 walkFn 函数进行处理。
// 文件处理函数定义如下,如果 WalkFunc 返回 nil,则 Walk 函数继续
// 遍历,如果返回 SkipDir,则 Walk 函数会跳过当前目录(如果当前遍
// 历到的是文件,则同时跳过后续文件及子目录),继续遍历下一个目录。
// 如果返回其它错误,则 Walk 函数会中止遍历过程。
// 在 Walk 遍历过程中,如果遇到错误,则会将错误通过 err 传递给
// WalkFunc 函数,同时 Walk 会跳过出错的项目,继续处理后续项目。

应用:

package main

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

func main() {
    gopath := os.Getenv("GOPATH")
    fmt.Printf("[%s/bin]\n", gopath)

    list := getShellScript(gopath)
    for i, p := range list {
        fmt.Printf("[%d:%s===%s]\n", i, path.Dir(p), path.Base(p))
    }

}

func getShellScript(rootpath string) []string {

    list := make([]string, 0, 10)
    
    err := filepath.Walk(rootpath, func(path string, info os.FileInfo, err error) error {
        if info.IsDir() {
            return nil
        }
        if filepath.Ext(path) == ".sh" {
            list = append(list, path)
        }
        return nil
    })
    if err != nil {
        fmt.Printf("walk error [%v]\n", err)
    }
    return list

}

输出:
[D:go_workspace/bin]
[0:.===D:go_workspacego_booksbuild-web-application-with-golangenbuild.sh]
[1:.===D:go_workspacego_booksbuild-web-application-with-golangjabuild.sh]
[2:.===D:go_workspacego_booksbuild-web-application-with-golangzhbuild.sh]
[3:.===D:go_workspacesrcgithub.comgolangprotobufptypesregen.sh]
[4:.===D:go_workspacesrcgithub.comjlaffayeftp.travisprepare.sh]
[5:.===D:go_workspacesrcgithub.commisheskathewaytogocode_exampleschapter_19goto_v5demo.sh]
[6:.===D:go_workspacesrcgithub.comqiniuapi.v6test_env.sh]
[7:.===D:go_workspacesrcthe_way_to_go_source_codethewaytogocode_exampleschapter_19goto_v5demo.sh]

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wangshubo1989/article/details/74330674
Last modification:November 20th, 2019 at 04:47 pm
如果觉得我的文章对你有用,请随意赞赏