Python glob多个文件类型

有没有更好的方式来使用Python中的glob.glob获取多种文件类型的列表,如.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   # the list of pdf and cpp files

也许还有另外一种方式,等待别人提出更好的答案。


连锁结果:

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

from glob import glob

files = glob('*.gif')
files.extend(glob('*.png'))
files.extend(glob('*.jpg'))

print(files)

如果您需要指定路径,请循环搜索匹配模式并将该连接保留在循环中以简化操作:

from os.path import join
from glob import glob

files = []
for ext in ('*.gif', '*.png', '*.jpg'):
   files.extend(glob(join("path/to/dir", ext)))

print(files)
链接地址: http://www.djcxy.com/p/3379.html

上一篇: Python glob multiple filetypes

下一篇: How to get the filename without the extension from a path in Python?