Go言語/filepathパッケージでパスとかファイル名とか拡張子を抜き出す
2021/01/15
Go言語でファイルパス文字列からパス名やファイル名、拡張子を抜き出すには、filepathパッケージを使います。
OSによって区切り文字が\だったり、/だったりしますが、OSに応じて切り替えてくれるから便利です。
package main
import (
"fmt"
"path/filepath"
)
func main() {
path_name := "/home/c340/Dropbox/_Source/go/test/test.go"
//パス名
fmt.Println(filepath.Dir(path_name))
//ファイル名
fmt.Println(filepath.Base(path_name))
//拡張子
fmt.Println(filepath.Ext(path_name))
//ファイルパスかどうかを判定してくれる
fmt.Println(filepath.IsAbs(path_name))
//連結してパスにしてくれる
fmt.Println(filepath.Join("/home", "c340", "test"))
}
出力結果は以下のとおりです。
/home/c340/Dropbox/_Source/go/test test.go .go true /home/c340/test
スポンサーリンク