Golang filepath包常用函數(shù)詳解
絕對路徑
絕對路徑時從根目錄開始的完整路徑,相對路徑是相對與當前工作目錄的路徑。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 函數(shù),分別獲取絕對路徑并判斷給定文件路徑是否為絕對路徑。
文件名和目錄
filepath.Base函數(shù)返回文件路徑的最后元素,通常為文件名。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函數(shù)清除重復和不規(guī)則的文件路徑,通過純詞法處理返回與指定路徑等效的最短路徑名。
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函數(shù)分割給定路徑為目錄和文件組件,filepath.SplitList函數(shù)分割一組由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函數(shù)在根目錄下遍歷文件樹。函數(shù)簽名為:
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函數(shù)返回模式匹配的文件名,不匹配則返回nil。函數(shù)簽名如下:
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 ccharacter-range:
c matches character c (c != '\\', '-', ']')
'\\' c matches character c
lo '-' hi matches character c for lo <= c <= hi
filepath.VolumeName
filepath.VolumeName函數(shù)基于文件路徑返回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包常用函數(shù)詳解的文章就介紹到這了,更多相關Go filepath內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Go語言如何使用golang-jwt/jwt/v4進行JWT鑒權詳解
最近項目中需要用到鑒權機制,golang中jwt可以用,這篇文章主要給大家介紹了關于Go語言如何使用golang-jwt/jwt/v4進行JWT鑒權的相關資料,需要的朋友可以參考下2022-09-09Go語言使用ioutil.ReadAll函數(shù)需要注意基本說明
這篇文章主要為大家介紹了Go語言使用ioutil.ReadAll函數(shù)需要注意基本說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-07-07