0

Essentially, I have a python script that takes a list of filenames as system arguments:

filelist = sys.argv[1:]

I'd like the file list to be all the files in the directory that begin with a certain prefix. I thought the best way to do this is using regular expressions, but I'm not sure how to get it to work.

That is, I'd like something like

python test.py '^ex'

to yield a filelist containing all the files in the working directory that start with "ex".

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
blep
  • 726
  • 1
  • 11
  • 28
  • a good resource here to understand regex: http://rubular.com/ – mika Feb 10 '13 at 22:33
  • 1
    The shell would do the right thing if you did ``python test.py ex*`` - it would create the list of filenames to be passed in as ``sys.argv[1:]`` - unless you're looking to take in a pattern and have something like ``glob.glob`` do the work for you. – sotapme Feb 10 '13 at 22:41
  • @sotapme: I knew it was something simple! Thanks. (I managed a more complicated version using [this](http://stackoverflow.com/a/3964691/743568), but your answer is much cleaner). If you want to post it below, I'll happily accept it. – blep Feb 10 '13 at 22:46
  • The other method is great for when your script wants to work filenames out, the shell thing is where the caller(shell) is telling the script what the filenames are - That's why Windows has historically been bad at filename expansion, I'm sure there was a time when every tool would have to implement a variation of shell globbing as ``cmd`` just passed in the cli parameters untouched, IIRC. – sotapme Feb 10 '13 at 22:51

1 Answers1

0

You don't necessarily need regex for this. A simple for loop could do the job. For example

for filename in filelist:
    if ex == filename[0:len(ex)]:
        newFileList.append(filename)

This haven't been tested out, minor adjustments might be needed. Of course, regex are great tools, but the above would be a simple alternative.

Sam
  • 794
  • 1
  • 7
  • 26
  • Your loop would probably work, except that I'd still have to input all of the files at the command line, or otherwise specify at the command line that it should go through all the files in the directory. sotapme's method in the comments above does solve this problem rather neatly, but thanks for pointing this out. – blep Feb 11 '13 at 01:51