[go] 파일 경로에서 디렉토리 목록 얻기

파일 경로에서 디렉토리 목록을 얻는 것은 Go 프로그래밍에서 자주 하는 작업 중 하나입니다. 이를 위해서 filepathos 패키지를 사용하여 파일 시스템 상의 디렉토리 목록을 얻을 수 있습니다.

파일 경로에서 디렉토리 목록 얻는 방법

다음은 Go 언어를 사용하여 파일 경로에서 디렉토리 목록을 얻는 간단한 예제입니다.

package main

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

func main() {
	dirPath := "/path/to/your/directory"
	
	dir, err := os.Open(dirPath)
	if err != nil {
		fmt.Println("Error opening directory:", err)
		return
	}
	defer dir.Close()
	
	fileList, err := dir.Readdir(0)
	if err != nil {
		fmt.Println("Error reading directory:", err)
		return
	}
	
	var directories []string
	for _, file := range fileList {
		if file.IsDir() {
			directories = append(directories, file.Name())
		}
	}
	
	fmt.Println("Directories in", dirPath, "are:")
	for _, dir := range directories {
		fmt.Println(dir)
	}
}

위의 예제 코드는 지정된 디렉토리에서 디렉토리 목록을 얻는 방법을 보여줍니다. os.Open을 사용하여 디렉토리를 열고, Readdir을 사용하여 디렉토리 내의 파일 및 디렉토리 목록을 얻습니다.

이제 위의 예제를 실행하면 해당 디렉토리의 모든 하위 디렉토리를 얻을 수 있습니다.

이제 Go를 사용하여 파일 경로에서 디렉토리 목록을 얻는 방법에 대해 알아보았습니다.

내용이 해당되었기를 바랍니다.