Given the following piece of python code:
for root, dirs, files in os.walk(directory):
for filename in fnmatch.filter(files, \'*.png\'):
pass
You can use a list comprehension to check if my_file
matches any of the file masks defined in patterns
:
import fnmatch
my_file = 'my_precious.txt'
patterns = ('*.txt', '*.html', '*.mp3')
if [pat for pat in patterns if fnmatch.fnmatch(my_file, pat)]:
print('We have a match!')
else:
print('No match')
This would be a better way, perhaps because you are not calling +
repeatedly and using a tuple
instead of list
.
for root, dirs, files in os.walk(directory):
for extension in ('*.jpg', '*.jpeg', '*.gif', '*.png'):
for filename in fnmatch.filter(files, extension):
pass
A tuple
is better because you are not going to modify the extension once you have created them. You are just using to iterate over them.