有没有更好的方法来使用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 os    
import glob
import operator
from functools import reduce

types = ('*.jpg', '*.png', '*.jpeg')
lazy_paths = (glob.glob(os.path.join('my_path', t)) for t in types)
paths = reduce(operator.add, lazy_paths, [])

https://docs.python.org/3.5/library/functools.html#functools.reduce https://docs.python.org/3.5/library/operator.html#operator.add

其他回答

从前面的答案

glob('*.jpg') + glob('*.png')

这是一个较短的问题,

from glob import glob
extensions = ['jpg', 'png'] # to find these filename extensions

# Method 1: loop one by one and extend to the output list
output = []
[output.extend(glob(f'*.{name}')) for name in extensions]
print(output)

# Method 2: even shorter
# loop filename extension to glob() it and flatten it to a list
output = [p for p2 in [glob(f'*.{name}') for name in extensions] for p in p2]
print(output)

来这里寻求帮助后,我有了自己的解决方案,想和大家分享。它基于user2363986的答案,但我认为这更具可伸缩性。这意味着,即使您有1000个扩展,代码仍然看起来很优雅。

from glob import glob

directoryPath  = "C:\\temp\\*." 
fileExtensions = [ "jpg", "jpeg", "png", "bmp", "gif" ]
listOfFiles    = []

for extension in fileExtensions:
    listOfFiles.extend( glob( directoryPath + extension ))

for file in listOfFiles:
    print(file)   # Or do other stuff

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

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

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

最简单的方法是使用itertools.chain

from pathlib import Path
import itertools

cwd = Path.cwd()

for file in itertools.chain(
    cwd.rglob("*.txt"),
    cwd.rglob("*.md"),
):
    print(file.name)

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

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

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