網(wǎng)站首頁 編程語言 正文
絕對(duì)路徑
絕對(duì)路徑時(shí)從根目錄開始的完整路徑,相對(duì)路徑是相對(duì)與當(dāng)前工作目錄的路徑。filepath.Abs 返回文件的絕對(duì)路徑,filepath.IsAbs 可以檢查給定路徑是否為絕對(duì)路徑。請(qǐng)看示例:
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ù),分別獲取絕對(duì)路徑并判斷給定文件路徑是否為絕對(duì)路徑。
文件名和目錄
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)) }
運(yùn)行程序分別打印出文件名和文件所在目錄。
filepath.Ext
filepath.Ext返回文件路徑中文件的擴(kuò)展名。
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) }
運(yùn)行程序,分別返回mp4和go擴(kuò)展名。
最短路徑
filepath.Clean函數(shù)清除重復(fù)和不規(guī)則的文件路徑,通過純?cè)~法處理返回與指定路徑等效的最短路徑名。
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)) } }
運(yùn)行程序輸出結(jié)果為:
$ 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) } }
上例中首先分割當(dāng)前工作目錄和用戶主目錄,然后把path變量的一組路徑分割為切片。
文件遍歷
filepath.Walk函數(shù)在根目錄下遍歷文件樹。函數(shù)簽名為:
func Walk(root string, fn WalkFunc) error
遍歷目錄樹下每個(gè)文件或目錄,包括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目錄下文件,列舉所有文本文件(擴(kuò)展名為txt的文件)。
文件名匹配
filepath.Glob函數(shù)返回模式匹配的文件名,不匹配則返回nil。函數(shù)簽名如下:
func Glob(pattern string) (matches []string, err error)
請(qǐng)下面示例代碼:
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) } }
上面示例列舉給定目錄下所有g(shù)o文件,**模式表示遞歸列舉。其他模式格式為:
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前導(dǎo)卷名稱,其他平臺(tái)返回空字符串。舉例:給定"C:\foo\bar" 在 Windows平臺(tái)返回 “C:”。 給定 “\host\share\foo” 返回 “\host\share”。其他平臺(tái)返回 “”。
請(qǐng)看示例:
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
相關(guān)推薦
- 2023-05-19 Python基于TensorFlow接口實(shí)現(xiàn)深度學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)回歸_python
- 2022-05-09 pytorch中的hook機(jī)制register_forward_hook_python
- 2022-08-23 python?matplotlib畫圖時(shí)坐標(biāo)軸重疊顯示不全和圖片保存時(shí)不完整的問題解決_python
- 2022-05-11 log4j2.xml 的標(biāo)簽 loggers 中 root 的屬性 level 指的是什么
- 2022-02-17 不懂就問:map中使用await為什么會(huì)失效?
- 2022-03-22 c語言求兩個(gè)字符串的交集_C 語言
- 2022-04-06 Android中卡頓優(yōu)化布局詳細(xì)介紹_Android
- 2022-12-06 Python基礎(chǔ)globlal?nonlocal和閉包函數(shù)裝飾器語法糖_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支