生命不止,继续 go go go !!!
文件以及文件夹的路径在编程中经常遇到,在C++工程中,我们往往自己写一个文件,里面塞满了关于路径的操作。
golang很好,为我们提供了path/filepath包,方便极了。
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
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)
}
输出:
\a\b\c\d
/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)
}
输出:
a\b\c
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 = filepath.Rel(`/a/b/c`,`a/b/d/e`)
fmt.Println(s,err)
}
输出:
d\e < nil>
d\e < 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
..\d\e < 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:
a\b\c
a\b\c
a\b\c
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.
获取 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_workspace\src\go_file_path\a\b\c\d
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,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_workspace\go_books\build-web-application-with-golang\en\build.sh]
[1:.===D:\go_workspace\go_books\build-web-application-with-golang\ja\build.sh]
[2:.===D:\go_workspace\go_books\build-web-application-with-golang\zh\build.sh]
[3:.===D:\go_workspace\src\github.com\golang\protobuf\ptypes\regen.sh]
[4:.===D:\go_workspace\src\github.com\jlaffaye\ftp.travis\prepare.sh]
[5:.===D:\go_workspace\src\github.com\misheska\thewaytogo\code_examples\chapter_19\goto_v5\demo.sh]
[6:.===D:\go_workspace\src\github.com\qiniu\api.v6\test_env.sh]
[7:.===D:\go_workspace\src\the_way_to_go_source_code\thewaytogo\code_examples\chapter_19\goto_v5\demo.sh]