Python globe breaks extension

I have python 2.7 and am trying to release:

glob('{faint,bright*}/{science,calib}/chip?/') 

I don't get any matches, however, from the shell echo {faint,bright*}/{science,calib}/chip? gives:

 faint/science/chip1 faint/science/chip2 faint/calib/chip1 faint/calib/chip2 bright1/science/chip1 bright1/science/chip2 bright1w/science/chip1 bright1w/science/chip2 bright2/science/chip1 bright2/science/chip2 bright2w/science/chip1 bright2w/science/chip2 bright1/calib/chip1 bright1/calib/chip2 bright1w/calib/chip1 bright1w/calib/chip2 bright2/calib/chip1 bright2/calib/chip2 bright2w/calib/chip1 bright2w/calib/chip2 

What is wrong with my expression?

+11
python bash shell glob
source share
4 answers

Since {} are not part of glob () in Python, what you probably want is something like

 import os import re ... match_dir = re.compile('(faint|bright.*)/(science|calib)(/chip)?') for dirpath, dirnames, filenames = in os.walk("/your/top/dir") if match_dir.search(dirpath): do_whatever_with_files(dirpath, files) # OR do_whatever_with_subdirs(dirpath, dirnames) 
+3
source share

{..} is known as bracket expansion and is a separate step that is applied before globalization occurs.

It is not part of globes and is not supported by the python glap function.

+5
source share

Try https://pypi.python.org/pypi/braceexpand

 pip install braceexpand 

Demo:

 >>> from braceexpand import braceexpand # Integer range >>> list(braceexpand('item{1..3}')) ['item1', 'item2', 'item3'] # Nested patterns >>> list(braceexpand('python{2.{5..7},3.{2,3}}')) ['python2.5', 'python2.6', 'python2.7', 'python3.2', 'python3.3'] 
+3
source share

As that other guy noted , Python does not support direct expansion of brackets. But since the expansion of the brackets is done before evaluating the wildcards, you can do it yourself, for example,

 result = glob('{faint,bright*}/{science,calib}/chip?/') 

becomes

 result = [ f for b in ['faint', 'bright*'] for s in ['science', 'calib'] for f in glob('{b}/{s}/chip?/'.format(b=b, s=s)) ] 
+2
source share

All Articles