[PYTHON] Recursively search all files with multiple specified extensions

It's a guy who wants to search for jpg or png in one shot. Even if I searched on the net, I couldn't do it in one line. But with recursion, I couldn't do it in one line ... It's python2.7.

Not recursion

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]])

Another. This one was a little faster.

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]))

Recursion

・ If the number is small, this is

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])

・ If there are many files, it will be difficult to list them.

import os

#Prepare a function to recursively get a file with 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)

Recommended Posts

Recursively search all files with multiple specified extensions
Search for files with the specified extension
Recursively unzip zip files with python
Load multiple JavaScript files with PyWebView
Generate all files with a specific extension
Delete all pyc files under the specified directory
Recursively search the specified directory to see the file
Configure a module with multiple files in Django
Convert multiple proto files at once with python
How to list files under the specified directory in a list (multiple conditions / subdirectory search)
Recursively search for files and directories in Python and output
Remove headings from multiple format CSV files with python