user1561868 user1561868 - 5 months ago 17
Python Question

regular expression using in glob.glob of python

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 is working to list files in current folder which have 'abc' '123' or 'a1b' in their names.
How to use one glob to made this function,thanks


The easiest way would be to filter the glob results yourself. Here is how to do it using a simple loop comprehension:

import glob
res = [f for f in glob.glob("*.txt") if "abc" in f or "123" in f or "a1b" in f]
for f in res:
    print f

You could also use a regexp and no glob:

import os
import re
res = [f for f in os.listdir(path) if'(abc|123|a1b).*\.txt$', f)]
for f in res:
    print f

(By the way, naming a variable list is a bad idea since list is a Python type...)