8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

指定した複数の拡張子のファイルを再帰的にすべて検索

Last updated at Posted at 2016-10-19

jpgとかpngとか一発で検索したいっていうやつです。
なんかネットで検索してもビシっと1行でやるのがなかったので。
でも再帰だとやっぱりビシッと1行でできなかった...
python2.7です。

#再帰じゃない

import glob
from compiler.ast import flatten

search_dir = "path/to/"
ext_list = ["jpg", "png"]

file_list = flatten([f for f in [glob.glob(search_dir + "*." + ext) for ext in ext_list]])

もうひとつ。
若干こっちの方が速かった。

import os
import glob
from itertools import chain

search_dir = "path/to/"
ext_list = ["jpg", "png"]

file_list = list(chain.from_iterable([glob.glob(os.path.join(search_dir, "*." + ext)) for ext in ext_list]))

#再帰

・数が少ないならこれで

import os

search_dir = "path/to/"
ext_list = ["jpg", "png"]

file_list = []
for root, dirs, files in os.walk(search_dir):
    for ext in ext_list:
        file_list.extend([os.path.join(root, file) for file in files if ext in file])

・ファイル数が多いとリストだと大変なので

import os

#yieldで再帰的にファイルを取得する関数を用意
def get_file_recursive(search_dir, ext_list):
    for root, dirs, files in os.walk(search_dir):
        for ext in ext_list:
            for file in [file for file in files if ext in file]:
                yield os.path.join(root, file)

search_dir = "path/to/"
ext_list = ["jpg", "png"]

file_list = get_file_recursive(search_dir, ext_list)
8
7
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
8
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?