tags:

views:

84

answers:

2

Greetings,

A script is working on one or more files. I want to pass the filenames (with regex in them) as arguments and put them in a list. What is the best way to do it?

For example I would accept the following arguments:

script.py file[1-3].nc #would create list [file1.nc, file2.nc, file3.nc] that I can work on
script.py file*.nc #would scan the folder for matching patterns and create a list
script.py file1.nc file15.nc booba[1-2].nc #creates [file1.nc, file15.nc, booba1.nc, booba2.nc]
+1  A: 

Updated: Under Unix, the shell will do the example expansions you want. Under Windows it won't, and then you need to use glob.glob().

But if you really do want regexp: Then you will simply have to list the directory, with listdir, and match the filenames with the regexp pattern. You'll also have to pass the parameter in quotes (at least under unix) so it doesn't expand it for you. :-)

Lennart Regebro
actually glob also supports ranges like [0-9].
Nick D
Forget regex, glob is built for precisely this. The example isn't really about regex anyway, since you want file*.nc to match file1.nc, file_fooey.nc, etc, not fil.nc, file.nc, fileeeee.nc, etc.And if Unix does the work for you, so much the better.
Ned Batchelder
@Nick D: Oh, I didn't know that. Well, then. glob it is.
Lennart Regebro
+4  A: 

The glob module is exactly what you are looking for

Check the examples:

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

You can use optparse or just sys.argv to get arguments. And pass them to glob.

Nadia Alramli