Search code examples
pythonregexfilesystemsglob

concise way to match filenames that end in certain extension in Python?


What's the canonical way to handle to retrieve all files in a directory that end in a particular extension, e.g. "All files that end in .ext or .ext2 in a case insensitive way?" One way is using os.listdir and re module:

import re
files = os.listdir(mydir)
# match in case-insensitive way all files that end in '.ext' or '.ext2'
p = re.compile(".ext(2)?$", re.IGNORECASE)
matching_files = [os.path.join(mydir, f) for f in files if p.search(x) is not None]

Is there a preferred way to do this more concisely with glob or fnmatch? The annoyance with listdir is that one has to handle the path all the time, by prepending with os.path.join the directory to the basename of each file it returns.


Solution

  • How about:

    >>> import glob
    >>> glob.glob("testdir/*")
    ['testdir/a.txt', 'testdir/b.txt', 'testdir/d.ext', 'testdir/c.ExT2']
    >>> [f for f in glob.glob("testdir/*") if f.lower().endswith((".ext", ".ext2"))]
    ['testdir/d.ext', 'testdir/c.ExT2']