From: https://stackoverflow.com/questions/2225564/get-a-filtered-list-of-files-in-a-directory
Method one:
glob.glob('145592*.jpg')
glob.glob()
is definitely the way to do it (as per Ignacio). However, if you do need more complicated matching, you can do it with a list comprehension and re.match()
, something like so:
files = [f for f in os.listdir('.') if re.match(r'[0-9]+.*\.jpg', f)]
Keep it simple:
import os
relevant_path = "[path to folder]"
included_extensions = ['jpg','jpeg', 'bmp', 'png', 'gif']
file_names = [fn for fn in os.listdir(relevant_path)
if any(fn.endswith(ext) for ext in included_extensions)]
Another option:
>>> import os, fnmatch
>>> fnmatch.filter(os.listdir('.'), '*.py')
['manage.py']
https://docs.python.org/3/library/fnmatch.html