LoginSignup
50
30

More than 5 years have passed since last update.

Golangでディレクトリ内のファイル一覧を入手する

Last updated at Posted at 2016-08-28

指定したディレクトリ配下にあるファイル一覧をスライスで返す。
サブディレクトリがあれば再帰で掘っていく。

main.go
package main

import (
    "fmt"
    "io/ioutil"
    "path/filepath"
)

func main() {
    fmt.Println(dirwalk("./test"))
}

func dirwalk(dir string) []string {
    files, err := ioutil.ReadDir(dir)
    if err != nil {
        panic(err)
    }

    var paths []string
    for _, file := range files {
        if file.IsDir() {
            paths = append(paths, dirwalk(filepath.Join(dir, file.Name()))...)
            continue
        }
        paths = append(paths, filepath.Join(dir, file.Name()))
    }

    return paths
}
$ ls
main.go test

$ tree test
test
├── file
├── test1
│   ├── file1-1
│   └── file1-2
└── test2
    ├── file2-1
    └── file2-2

2 directories, 5 files

$ go run main.go
[test/file test/test1/file1-1 test/test1/file1-2 test/test2/file2-1 test/test2/file2-2]
50
30
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
50
30