Adam_G
Adam_G

Reputation: 7879

Read a list of subdirectories from command line arguement

I would like to pass in multiple command line arguments to create a list of subdirectories to read. Currently I pass them in from the command line as:

python foo.py -s 'P1,P2' -c 'X,Y'

I would like this to read only the subdirectories:

P1/X/
P1/Y/
P2/X/
P2/Y/

I've tried the below, but it ends up reading every subdirectory:

path = os.path.join('*['+s+']', '*['+c+']', '*.txt') 
    files = glob.glob(path)

How can I limit this to only those subdirectories from the combination of lists?

Upvotes: 0

Views: 52

Answers (1)

kdopen
kdopen

Reputation: 8215

The following will do what you want, in terms of generating the list

>>> import os
>>> from itertools import product
>>> [os.path.join(s, c, '*.txt') for s, c in product(['P1', 'P2'], ['X', 'Y'])]
['P1/X/*.txt', 'P1/Y/*.txt', 'P2/X/*.txt', 'P2/Y/*.txt']

Obviously, you'll need to turn your two arguments into two lists to feed to the product function.

Upvotes: 1

Related Questions