LoginSignup
15
12

More than 5 years have passed since last update.

Go でフォルダに含まれる特定の拡張子のファイルだけ列挙するには path/filepath を使う

Last updated at Posted at 2014-06-27

概要

フォルダに含まれる特定の拡張子のファイルだけを処理したいときには,filepath.Glob(pattern string) が超便利!

サンプル

ディレクトリを指定してその下のcsvファイルを列挙する
package main

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

func main() {
    targetDir := "."
    if len(os.Args) == 2 {
        targetDir = os.Args[1]
    }
    pattern := targetDir + "/*.csv"
    files, err := filepath.Glob(pattern)
    if err != nil {
        panic(err)
    }
    for _, file := range files {
        fmt.Println(file)
    }
}
実行例
% go run filepath_sample.go ../kagome/dic/_converter/mecab-ipadic-2.7.0-20070801                                                                    
../kagome/dic/_converter/mecab-ipadic-2.7.0-20070801/Adj.csv
../kagome/dic/_converter/mecab-ipadic-2.7.0-20070801/Adnominal.csv
../kagome/dic/_converter/mecab-ipadic-2.7.0-20070801/Adverb.csv
../kagome/dic/_converter/mecab-ipadic-2.7.0-20070801/Auxil.csv
../kagome/dic/_converter/mecab-ipadic-2.7.0-20070801/Conjunction.csv
…snip

ディレクトリの指定にも * が使える!

2階層下のフォルダのファイルを列挙する
package main

import (
        "fmt"
        "path/filepath"
)

func main() {
        pattern := "./*/*/*.csv"
        files, err := filepath.Glob(pattern)
        if err != nil {
                panic(err)
        }
        for _, file := range files {
                fmt.Println(file)
        }
}
こんな感じのディレクトリ構造で実行すると・・・
% tree a                                                                                                                                            
a
├── a.csv
├── b
│   └── b.csv
└── c
    └── c.csv
% go run filepath_sample.go                                                                                                                         
a/b/b.csv
a/c/c.csv

おお!便利.

15
12
0

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
15
12