1

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
  • If you are on a linux system using the normal shells, you'll have to properly quote those arguments if you expect them to be passed unadulterated to your script: script.py 'file[1-3].nc' Commented Sep 16, 2009 at 10:55

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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. :-)

3 Comments

actually glob also supports ranges like [0-9].
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.
@Nick D: Oh, I didn't know that. Well, then. glob it is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.