在python glob中支持扩展

时间:2014-04-10 18:55:04

标签: python bash shell glob expansion

我有python 2.7,我正在尝试发布:

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

我没有获得匹配,但是来自shell echo {faint,bright*}/{science,calib}/chip?给出了:

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

我的表情有什么问题?

4 个答案:

答案 0 :(得分:6)

{..}被称为大括号扩展,是在发生全局变换之前应用的单独步骤。

它不是globs的一部分,并且不受python glob函数的支持。

答案 1 :(得分:3)

由于{}不是Python中的glob(),你可能想要的是

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)

答案 2 :(得分:3)

尝试https://pypi.python.org/pypi/braceexpand

pip install braceexpand

演示:

>>> 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 :(得分:2)

作为that other guy pointed out,Python不直接支持大括号扩展。但是,由于大括号扩展是在评估通配符之前完成的,因此您可以自己完成,例如

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

变为

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