135
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

posted at

updated at

Organization

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

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

関連記事

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Sign upLogin
135
Help us understand the problem. What are the problem?