patternpythonMinor
Pythonic way for double iteration (list all files with extensions)
Viewed 0 times
pythonicallwithextensionswayiterationdoublefilesforlist
Problem
Given a base path and a list with extensions the task is to list all files:
Two of my solutions are:
Have you got any other ideas?
Two of my solutions are:
from glob import glob
from os import path
EXTENSIONS = ['*.zip', '*.jar', '*.pdf']
DOC_PATH = '/path/to/files'
# Solution1:
files = []
for ext in EXTENSIONS:
files.extend(glob(path.join(DOC_PATH, ext)))
# works but looks very clumsy
# Solution2:
files = reduce(lambda x,y: x+y,
[glob(path.join(DOC_PATH, ext)) for ext in EXTENSIONS])
# Also functional but looks like a misuse of reduceHave you got any other ideas?
Solution
If you only need to iterate over them (once) and not an actual list, you could use
If you do need an actual list, you can further call
itertools.chain and glob.iglob:files = chain(*(iglob(path.join(DOC_PATH, ext)) for ext in EXTENSIONS))If you do need an actual list, you can further call
list(files), of course.Code Snippets
files = chain(*(iglob(path.join(DOC_PATH, ext)) for ext in EXTENSIONS))Context
StackExchange Code Review Q#56332, answer score: 3
Revisions (0)
No revisions yet.