regular expression usage in glob.glob for python

前端 未结 4 675
我在风中等你
我在风中等你 2020-11-27 05:38
import glob

list = glob.glob(r\'*abc*.txt\') + glob.glob(r\'*123*.txt\') + glob.glob(r\'*a1b*.txt\')

for i in list:
  print i

This code works to

4条回答
  •  没有蜡笔的小新
    2020-11-27 06:25

    Here is a ready to use way of doing this, based on the other answers. It's not the most performance critical, but it works as described;

    def reglob(path, exp, invert=False):
        """glob.glob() style searching which uses regex
    
        :param exp: Regex expression for filename
        :param invert: Invert match to non matching files
        """
    
        m = re.compile(exp)
    
        if invert is False:
            res = [f for f in os.listdir(path) if m.search(f)]
        else:
            res = [f for f in os.listdir(path) if not m.search(f)]
    
        res = map(lambda x: "%s/%s" % ( path, x, ), res)
        return res
    

提交回复
热议问题