[go] 경로 확장자

Go 언어에서 파일 시스템을 다룰 때는 파일 경로와 확장자를 다루는 일이 빈번합니다. 이번에는 Go 언어에서 경로 및 확장자를 다루는 방법에 대해 알아봅시다.

경로 다루기

Go 언어에서 파일 경로를 다루기 위해서는 path/filepath 패키지를 사용합니다. 해당 패키지에는 파일 경로를 조작하고 검색하는 데 필요한 함수들이 제공됩니다. 예를 들어, 다음은 파일 경로를 조작하는 간단한 예제입니다.

package main

import (
	"fmt"
	"path/filepath"
)

func main() {
	// 기본 경로
	basePath := "/usr/local/bin"
	// 파일 이름
	fileName := "test.txt"

	// 파일 경로 생성
	fullPath := filepath.Join(basePath, fileName)
	fmt.Println("Full path:", fullPath)

	// 파일의 디렉토리 경로
	dir := filepath.Dir(fullPath)
	fmt.Println("Directory:", dir)

	// 파일 이름과 확장자 분리
	name, ext := filepath.Split(fullPath)
	fmt.Println("File name:", name)
	fmt.Println("Extension:", ext)

	// 파일 확장자 추출
	fileExt := filepath.Ext(fullPath)
	fmt.Println("File extension:", fileExt)
}

확장자 다루기

파일 경로에서 확장자를 다루기 위해서는 path/filepath 패키지를 사용하거나, strings 패키지의 함수를 활용할 수 있습니다. 해당 패키지들을 사용하여 파일 경로로부터 확장자를 추출하거나, 확장자의 존재 여부를 확인할 수 있습니다.

package main

import (
	"fmt"
	"path/filepath"
	"strings"
)

func main() {
	filePath := "/usr/local/bin/test.txt"

	// 확장자 추출 - filepath
	ext := filepath.Ext(filePath)
	fmt.Println("Extension (filepath):", ext)

	// 확장자 추출 - strings
	parts := strings.Split(filePath, ".")
	if len(parts) > 1 {
		ext2 := parts[len(parts)-1]
		fmt.Println("Extension (strings):", ext2)
	} else {
		fmt.Println("No extension found")
	}

	// 특정 확장자 확인
	isTxt := strings.HasSuffix(filePath, ".txt")
	fmt.Println("Is txt file:", isTxt)
}

위의 예제 코드를 통해, Go 언어에서 파일 경로와 확장자를 다루는 방법에 대해 알아보았습니다. 파일 시스템을 다루는 프로그램을 작성할 때 유용하게 활용할 수 있을 것입니다.

참고 문헌: Go언어 공식 문서

이제 Go 언어에서 파일 경로와 확장자를 다루는 방법을 알게 되었습니다. 본 포스팅이 도움이 되었기를 바랍니다!