LoginSignup
144
134

More than 5 years have passed since last update.

Pythonで再帰的にファイル・ディレクトリを探して出力する

Last updated at Posted at 2013-07-11

Pythonで再帰的に全てのファイルやディレクトリのリストを作るときは、os.walk()とジェネレーター(yield)を組み合わせた関数を作っとくと楽。

例えばこんなディレクトリ構成
$ tree /tmp/test
/tmp/test
├── 1
│   ├── a
│   │   ├── A
│   │   ├── B
│   │   └── hoge
│   └── b
│       ├── A
│       ├── B
│       └── hoge
└── 2
    ├── bar
    ├── c
    │   ├── buzz
    │   └── fizz
    └── foo

9 directories, 6 files
import os

def find_all_files(directory):
    for root, dirs, files in os.walk(directory):
        yield root
        for file in files:
            yield os.path.join(root, file)

for file in find_all_files('/tmp/test'):
    print file
出力
/tmp/test
/tmp/test/1
/tmp/test/1/a
/tmp/test/1/a/hoge
/tmp/test/1/a/A
/tmp/test/1/a/B
/tmp/test/1/b
/tmp/test/1/b/hoge
/tmp/test/1/b/A
/tmp/test/1/b/B
/tmp/test/2
/tmp/test/2/bar
/tmp/test/2/foo
/tmp/test/2/c
/tmp/test/2/c/buzz
/tmp/test/2/c/fizz

関連記事

144
134
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
144
134