go言語 パスからフォルダとファイル名を分割する

  • 作成日 2021.06.08
  • 更新日 2022.10.28
  • go
go言語 パスからフォルダとファイル名を分割する

go言語で、ライブラリfilepathのSplitを使用して、パスからフォルダとファイル名を分割するサンプルコードを記述してます。go言語のバージョンは1.15.4を使用してます。

環境

  • OS windows10 pro 64bit
  • go言語 1.15.4

Split使い方

Splitを使用すれば、パスからフォルダとファイル名を分割することが可能です。

d, f := filepath.Split(`PATH`)

// d フォルダ
// f ファイル

以下は、指定したパスをフォルダとファイル名に分割するサンプルコードとなります。

package main

import (
	"fmt"
	"path/filepath"
)

func main() {

	d, f := filepath.Split(`C:\sample_go\sample.go`)

	fmt.Println(d, f)
	// C:\sample_go\ sample.go

	d, f = filepath.Split(`C:\sample_go\test`)

	fmt.Println(d, f)
	// C:\sample_go\ test

	d, f = filepath.Split(`C:\sample_go`)

	fmt.Println(d, f)
	// C:\ sample_go
}

windowsとcentos8では、区切り文字が違うので同じコードを実行した場合は分割されません。

 C:\sample_go\sample.go
 C:\sample_go\test
 C:\sample_go