Search for a file using a wildcard

Stan picture Stan · Jul 28, 2010 · Viewed 71.1k times · Source

I want get a list of filenames with a search pattern with a wildcard. Like:

getFilenames.py c:\PathToFolder\*
getFilenames.py c:\PathToFolder\FileType*.txt
getFilenames.py c:\PathToFolder\FileTypeA.txt

How can I do this?

Answer

Martin picture Martin · Jul 28, 2010

You can do it like this:

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

Note: If the directory contains files starting with . they won’t be matched by default. For example, consider a directory containing card.gif and .card.gif:

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

This comes straight from here: http://docs.python.org/library/glob.html