寫一個小函數測試:
func DumpPath(path string) {
m := make(map[string]string)函數
base := filepath.Base(path)
ext := filepath.Ext(path)
dir,file := filepath.Split(path)測試
m["path"] = path
m["base"] = base
m["ext"] = ext
m["dir"] = dir
m["file"] = file
for k,v := range m {
fmt.Println(k , ":", v)
}
}component
-------------------------------------------------------------------------------------element
CASE 1:rem
path : ../data/test_1.txt
base : test_1.txt
ext : .txt
dir : ../data/
file : test_1.txt文檔
容易覺得base 和 file是一個意思。可是不是的。string
-------------------------------------------------------------------------------------it
CASE 2:ast
ext :
dir : d:
file :
path : d:
base : \test
此爲官方文檔解釋:
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.
路徑被分解,最後的一個就是Base.
Split splits path immediately following the final Separator, separating it into a directory and file name component. If there is no Separator in path, Split returns an empty dir and file set to path. The returned values have the property that path = dir+file.
公式:path = dir+file 好理解。
就是路徑是由目錄和文件名串起來的。
按照這個規則,Join就是逆過程。
fmt.Println(filepath.Join("c:/", "b","a", ".txt"))
c:\b\a\.txt
因此想獲得c:\b\a.txt
要用 filepath.Join("c:/", "b","a.txt")
*****
Go細緻的地方,後綴中是帶有 . 號的。
常見的一個操做就是去掉文件的後綴。
strings.TrimSuffix(path, filepath.Ext(path))
這個符合一個規定就是:file = name + ext
那個「."號屬於後綴。