網(wǎng)站首頁 編程語言 正文
絕對路徑
絕對路徑時從根目錄開始的完整路徑,相對路徑是相對與當前工作目錄的路徑。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)) }
原文鏈接:https://blog.csdn.net/neweastsun/article/details/128792296
相關推薦
- 2022-04-14 解決:Failed to run File Watcher ‘goimports‘.The watc
- 2022-08-30 Python?selenium下拉選擇框實戰(zhàn)應用例子_python
- 2022-10-22 Python基礎Lists和tuple實例詳解_python
- 2022-04-28 C#實現(xiàn)Windows服務測試與調試_C#教程
- 2022-12-10 Android入門之日歷選擇與時間選擇組件的使用_Android
- 2023-05-08 Python中Generators教程的實現(xiàn)_python
- 2022-08-28 centos 單機版redis安裝與數(shù)據(jù)持久化
- 2022-08-01 OpenCV連通域數(shù)量統(tǒng)計學習示例_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支