Go语言学习之path/filepath包(the way to go)
生命不止,继续 go go go !!! 文件以及文件夹的路径在编程中经常遇到,在C++工程中,我们往往自己写一个文件,里面塞满了关于路径的操作。 golang很好,为我们提供了path/filepath包,方便极了。 import “path/filepath” 常量 const (
Separator = os.PathSeparator
ListSeparator = os.PathListSeparator
)
ToSlash func ToSlash(path string) string
ToSlash returns the result of replacing each separator character in path with a slash (‘/’) character. Multiple separators are replaced by multiple slashes. 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. 应用: 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)
}
输出: Dir func Dir(path string) string
Dir returns all but the last element of path,typically the path’s directory. 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 中最后一个分隔符前后的两部分,之前包含分隔符,之后不包含分隔符 // 获取路径字符串中的文件扩展名 应用: 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)
}
输出: 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. 应用: 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 = filepath.Rel(`/a/b/c`,`a/b/d/e`)
fmt.Println(s,err)
}
输出: 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"))
}
输出: 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. IsAbs 应用: package main
import (
"fmt"
"path/filepath"
)
func main() {
s1 := `a/b/c/d`
fmt.Println(filepath.Abs(s1)) // 不同系统显示不一样
s2 := `D:go_workspacesrcgo_file_pathabcd`
fmt.Println(filepath.IsAbs(s1)) // false
fmt.Println(filepath.IsAbs(s2)) // true
}
输出: Match(pattern,name string) (matched bool,err error) // pattern 规则如下: 应用: 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,filename)
if err != nil {
fmt.Println(err)
}
fmt.Println(matched)
}
输出: Walk(root string,walkFn WalkFunc) error 应用: 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
}
输出: 参考:http://www.cnblogs.com/golove/p/5903579.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |