regex - concise way to match filenames that end in certain extension in Python? -
what's canonical way handle retrieve files in directory end in particular extension, e.g. "all files end in .ext
or .ext2
in case insensitive way?" 1 way using os.listdir
, re
module:
import re files = os.listdir(mydir) # match in case-insensitive way files end in '.ext' or '.ext2' p = re.compile(".ext(2)?$", re.ignorecase) matching_files = [os.path.join(mydir, f) f in files if p.search(x) not none]
is there preferred way more concisely glob
or fnmatch
? annoyance listdir
1 has handle path time, prepending os.path.join
directory basename of each file returns.
how about:
>>> import glob >>> glob.glob("testdir/*") ['testdir/a.txt', 'testdir/b.txt', 'testdir/d.ext', 'testdir/c.ext2'] >>> [f f in glob.glob("testdir/*") if f.lower().endswith((".ext", ".ext2"))] ['testdir/d.ext', 'testdir/c.ext2']
python regex filesystems glob
No comments:
Post a Comment