[go] path/filepath 패키지 메서드
이번에는 Go 언어에서 파일 경로를 다루는데 유용한 path/filepath
패키지의 메서드에 대해 알아보겠습니다.
1. 파일 경로 조작
먼저, 파일 경로를 조작하는데 사용되는 몇 가지 유용한 메서드를 살펴보겠습니다.
Join
package main
import (
"fmt"
"path/filepath"
)
func main() {
dir := "/usr"
file := "local"
path := filepath.Join(dir, file)
fmt.Println(path) // 출력: /usr/local
}
Base
package main
import (
"fmt"
"path/filepath"
)
func main() {
file := "/home/user/test.txt"
base := filepath.Base(file)
fmt.Println(base) // 출력: test.txt
}
Dir
package main
import (
"fmt"
"path/filepath"
)
func main() {
file := "/home/user/test.txt"
dir := filepath.Dir(file)
fmt.Println(dir) // 출력: /home/user
}
2. 경로 확인
파일 경로를 확인하거나 경로 관련 작업을 수행하는데 유용한 메서드를 살펴보겠습니다.
IsAbs
package main
import (
"fmt"
"path/filepath"
)
func main() {
path1 := "home/user/test.txt"
path2 := "/home/user/test.txt"
fmt.Println(filepath.IsAbs(path1)) // 출력: false
fmt.Println(filepath.IsAbs(path2)) // 출력: true
}
Clean
package main
import (
"fmt"
"path/filepath"
)
func main() {
path := "/home/../user/./test.txt"
cleanPath := filepath.Clean(path)
fmt.Println(cleanPath) // 출력: /user/test.txt
}
결론
path/filepath
패키지의 메서드를 적절히 활용하면 파일 경로를 조작하고 확인하는 작업을 쉽게 할 수 있습니다. 이러한 메서드들은 파일 시스템과 관련된 작업을 하는 프로그램을 개발할 때 매우 유용합니다.
더 많은 정보는 공식 Go 문서를 참고하세요.