Código preliminar
import glob
import fnmatch
import pathlib
import os
pattern = '*.py'
path = '.'
Solución 1 - use "glob"
# lookup in current dir
glob.glob(pattern)
In [2]: glob.glob(pattern)
Out[2]: ['wsgi.py', 'manage.py', 'tasks.py']
Solución 2 - use "os" + "fnmatch"
Variante 2.1 - Búsqueda en el directorio actual
# lookup in current dir
fnmatch.filter(os.listdir(path), pattern)
In [3]: fnmatch.filter(os.listdir(path), pattern)
Out[3]: ['wsgi.py', 'manage.py', 'tasks.py']
Variante 2.2 - Búsqueda recursiva
# lookup recursive
for dirpath, dirnames, filenames in os.walk(path):
if not filenames:
continue
pythonic_files = fnmatch.filter(filenames, pattern)
if pythonic_files:
for file in pythonic_files:
print('{}/{}'.format(dirpath, file))
Resultado
./wsgi.py
./manage.py
./tasks.py
./temp/temp.py
./apps/diaries/urls.py
./apps/diaries/signals.py
./apps/diaries/actions.py
./apps/diaries/querysets.py
./apps/library/tests/test_forms.py
./apps/library/migrations/0001_initial.py
./apps/polls/views.py
./apps/polls/formsets.py
./apps/polls/reports.py
./apps/polls/admin.py
Solución 3 - use "pathlib"
# lookup in current dir
path_ = pathlib.Path('.')
tuple(path_.glob(pattern))
# lookup recursive
tuple(path_.rglob(pattern))
Notas:
- Probado en Python 3.4
- El módulo "pathlib" se agregó solo en Python 3.4
- Python 3.5 agregó una función para la búsqueda recursiva con glob.glob
https://docs.python.org/3.5/library/glob.html#glob.glob . Como mi máquina está instalada con Python 3.4, no lo he probado.