Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした