List comprehensions and glob

Peter Otten __peter__ at web.de
Thu Jul 15 05:05:19 EDT 2004


Robin Becker wrote:

> I want to use a list of glob patterns to create a single flat list of
> files
> 
> eg
> 
> P = ['*.txt','*.py']
> 
> I expected I would somehow be able to use list comprehensions to do
> this, but in the end I could only do this hackish thing
> 
> import operator, glob
> F = reduce(operator.add,[glob.glob(p) for p in P],[])
> 
> 
> is there a more pythonic approach?

Here's how I would do it in 2.4:

patterns = ["*.txt", "*.py"]

def matchAny(name, patterns):
    return True in (fnmatch.fnmatch(name, p) for p in patterns)

matches = [fn for fn in os.listdir(".") if matchAny(fn, patterns)]

Note that the result is slightly different: files starting with a dot are
not filtered out.

Peter





More information about the Python-list mailing list