When recursively creating a list of all files and directories in Python, it's easier to create a function that combines ʻos.walk () and a generator (
yield`).
For example, this directory structure
$ 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
output
/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
RecursiveIteratorIterator
Recommended Posts