← retour aux snippets

fnmatch: filtrer avec motifs glob

Sélectionner des noms de fichiers selon des motifs style shell.

python filesystem #fnmatch#glob#filter

objectif

Sélectionner des noms de fichiers selon des motifs style shell.

code minimal

import fnmatch
files = ["a.py", "b.txt", "c.py"]
py = fnmatch.filter(files, "*.py")
print(py == ["a.py","c.py"])  # attendu: True

utilisation

import fnmatch
print(fnmatch.fnmatch("data_2025.csv", "data_*.csv"))

variante(s) utile(s)

import fnmatch
names = ["IMG_001.JPG", "img_002.jpg"]
print([n for n in names if fnmatch.fnmatch(n.lower(), "*.jpg")] == names)

notes

  • Sensible à la casse selon la plateforme (Windows non, Unix oui).
  • Pour explorer le disque, combinez avec os.listdir() ou Path.glob().