[go] 경로 분리

파일 경로에서 디렉토리 경로와 파일 이름을 분리해야 하는 경우가 있습니다. 예를 들어, /Users/johndoe/Documents/example.txt와 같은 파일 경로를 사용하고 있을 때, 이를 디렉토리 경로(/Users/johndoe/Documents)와 파일 이름(example.txt)으로 분리해야 할 수 있습니다.

이를 위해 Go 언어에서는 path/filepath 패키지를 사용하여 경로를 분리할 수 있습니다.

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	fullPath := "/Users/johndoe/Documents/example.txt"

	dir, file := filepath.Split(fullPath)

	fmt.Println("디렉토리 경로:", dir)
	fmt.Println("파일 이름:", file)
}

위 예제 코드에서 filepath.Split 함수를 이용하여 전체 파일 경로를 디렉토리 경로와 파일 이름으로 분리합니다. 그러면 dir 변수에는 /Users/johndoe/Documents/이, file 변수에는 example.txt가 각각 저장됩니다.

이제 위의 예제 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.

디렉토리 경로: /Users/johndoe/Documents/
파일 이름: example.txt

이렇게 하면 파일 경로에서 디렉토리 경로와 파일 이름을 쉽게 분리할 수 있습니다.

참고 자료