有没有更好的方法来使用glob。Glob在python中获取多个文件类型的列表,如.txt, .mdown和.markdown?现在我有这样的东西:

projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob( os.path.join(projectDir, '*.markdown') )

当前回答

也许有更好的办法,但是:

import glob
types = ('*.pdf', '*.cpp') # the tuple of file types
files_grabbed = []
for files in types:
    files_grabbed.extend(glob.glob(files))

# files_grabbed is the list of pdf and cpp files

也许还有其他的方法,所以等待别人提出更好的答案。

其他回答

对于glob,这是不可能的。你只能使用: *匹配所有内容 ? 匹配任何单个字符 [seq]匹配seq中的任意字符 [!Seq]匹配任何不在Seq中的字符

使用操作系统。Listdir和regexp检查模式:

for x in os.listdir('.'):
  if re.match('.*\.txt|.*\.sql', x):
    print x

也许有更好的办法,但是:

import glob
types = ('*.pdf', '*.cpp') # the tuple of file types
files_grabbed = []
for files in types:
    files_grabbed.extend(glob.glob(files))

# files_grabbed is the list of pdf and cpp files

也许还有其他的方法,所以等待别人提出更好的答案。

与@BPL相同的答案(计算效率高),但它可以处理任何glob模式,而不是扩展:

import os
from fnmatch import fnmatch

folder = "path/to/folder/"
patterns = ("*.txt", "*.md", "*.markdown")

files = [f.path for f in os.scandir(folder) if any(fnmatch(f, p) for p in patterns)]

这种解决方案既高效又方便。它还与glob的行为紧密匹配(请参阅文档)。

注意,使用内置包pathlib会更简单:

from pathlib import Path

folder = Path("/path/to/folder")
patterns = ("*.txt", "*.md", "*.markdown")

files = [f for f in folder.iterdir() if any(f.match(p) for p in patterns)]

这是一个Python 3.4+ pathlib解决方案:

exts = ".pdf", ".doc", ".xls", ".csv", ".ppt"
filelist = (str(i) for i in map(pathlib.Path, os.listdir(src)) if i.suffix.lower() in exts and not i.stem.startswith("~"))

此外,它会忽略所有以~开头的文件名。

Python 3

我们可以使用pathlib;.glob仍然不支持对多个参数或在大括号内(如POSIX shell)进行通配符操作,但我们可以轻松地过滤结果。

例如,理想情况下你可能喜欢做的事情:

# NOT VALID
Path(config_dir).glob("*.{ini,toml}")
# NOR IS
Path(config_dir).glob("*.ini", "*.toml")

你可以:

filter(lambda p: p.suffix in {".ini", ".toml"}, Path(config_dir).glob("*"))

这也不算太糟。