有没有更好的方法来使用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') )

当前回答

还有另一个解决方案(使用glob使用多个匹配模式获取路径,并使用reduce和add将所有路径组合到一个列表中):

import functools, glob, operator
paths = functools.reduce(operator.add, [glob.glob(pattern) for pattern in [
    "path1/*.ext1",
    "path2/*.ext2"]])

其他回答

import os
import glob

projectFiles = [i for i in glob.glob(os.path.join(projectDir,"*")) if os.path.splitext(i)[-1].lower() in ['.txt','.markdown','.mdown']]

Os.path.splitext将返回filename & .extension

filename, .extension = os.path.splitext('filename.extension')

.lower()将字符串转换为小写

这应该有用:

import glob
extensions = ('*.txt', '*.mdown', '*.markdown')
for i in extensions:
    for files in glob.glob(i):
        print (files)

也许我遗漏了一些东西但如果只是简单的glob也许你可以这样做?

projectFiles = glob.glob(os.path.join(projectDir, '*.{txt,mdown,markdown}'))

链接结果:

import itertools as it, glob

def multiple_file_types(*patterns):
    return it.chain.from_iterable(glob.iglob(pattern) for pattern in patterns)

然后:

for filename in multiple_file_types("*.txt", "*.sql", "*.log"):
    # do stuff

你可以用这个:

project_files = []
file_extensions = ['txt','mdown','markdown']
for file_extension in file_extensions:
    project_files.extend(glob.glob(projectDir  + '*.' + file_extension))