Kode awal
import glob
import fnmatch
import pathlib
import os
pattern = '*.py'
path = '.'
Solusi 1 - gunakan "glob"
# lookup in current dir
glob.glob(pattern)
In [2]: glob.glob(pattern)
Out[2]: ['wsgi.py', 'manage.py', 'tasks.py']
Solusi 2 - gunakan "os" + "fnmatch"
Varian 2.1 - Pencarian dalam direktori saat ini
# 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']
Varian 2.2 - Pencarian rekursif
# 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))
Hasil
./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
Solusi 3 - gunakan "pathlib"
# lookup in current dir
path_ = pathlib.Path('.')
tuple(path_.glob(pattern))
# lookup recursive
tuple(path_.rglob(pattern))
Catatan:
- Diuji pada Python 3.4
- Modul "pathlib" ditambahkan hanya dalam Python 3.4
- Python 3.5 menambahkan fitur untuk pencarian rekursif dengan glob.glob
https://docs.python.org/3.5/library/glob.html#glob.glob . Karena mesin saya diinstal dengan Python 3.4, saya belum mengujinya.