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:
在以特定扩展结束的目录中检索所有文件的标准方法是什么?“所有的文件都以。ext或。ext2结尾,不区分大小写吗?”一种方法是使用操作系统。listdir和re模块:
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.
使用glob或fnmatch有更简洁的方法吗?listdir带来的麻烦是,必须始终通过使用os.path预挂来处理路径。将目录连接到它返回的每个文件的basename。
1 个解决方案
#1
3
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']
#1
3
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']