10.7. glob — Recherche de chemins de style Unix selon certains motifs

Code source : Lib/glob.py


The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell. Note that unlike fnmatch.fnmatch(), glob treats filenames beginning with a dot (.) as special cases. (For tilde and shell variable expansion, use os.path.expanduser() and os.path.expandvars().)

Pour une correspondance littérale, il faut entourer le métacaractère par des crochets. Par exemple, '[?]' reconnaît le caractère '?'.

glob.glob(pathname)

Renvoie une liste, potentiellement vide, de chemins correspondant au motif pathname, qui doit être une chaîne de caractères contenant la spécification du chemin. pathname peut être soit absolu (comme /usr/src/Python-1.5/Makefile) soit relatif (comme ../../Tools/*/*.gif), et contenir un caractère de remplacement de style shell. Les liens symboliques cassés sont aussi inclus dans les résultats (comme pour le shell).

glob.iglob(pathname)

Renvoie un iterator qui produit les mêmes valeurs que glob(), sans toutes les charger en mémoire simultanément.

Nouveau dans la version 2.5.

For example, consider a directory containing only the following files: 1.gif, 2.txt, and card.gif. glob() will produce the following results. Notice how any leading components of the path are preserved.

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']

Si le répertoire contient des fichiers commençant par ., ils ne sont pas reconnus par défaut. Par exemple, considérons un répertoire contenant card.gif et .card.gif :

>>> import glob
>>> glob.glob('*.gif')
['card.gif']
>>> glob.glob('.c*')
['.card.gif']

Voir aussi

Module fnmatch

Recherche de noms de fichiers de style shell (ne concerne pas les chemins)