views:

142

answers:

3

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

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

How to do this? Thanks.

+3  A: 

Like this:

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

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

Martin
+2  A: 
from glob import glob
import sys

files = glob(sys.argv[1])
Daniel Egeberg
+1  A: 

glob is useful if you are doing this in within python, however, your shell may not be passing in the * (I'm not familiar with the windows shell).

For example, when I do the following:

import sys
print sys.argv

On my shell, I type:

$ python test.py *.jpg

I get this:

['test.py', 'test.jpg', 'wasp.jpg']

Notice that argv does not contain "*.jpg"

The important lesson here is that most shells will expand the asterisk at the shell, before it is passed to your application.

In this case, to get the list of files, I would just do sys.argv[1:]. Alternatively, you could escape the *, so that python sees the literal *. Then, you can use the glob module.

$ getFileNames.py "*.jpg"

or

$ getFileNames.py \*.jpg
orangeoctopus