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