使用fnmatch.filter通过多个可能的文件扩展名过滤文件 [英] Use fnmatch.filter to filter files by more than one possible file extension

查看:473
本文介绍了使用fnmatch.filter通过多个可能的文件扩展名过滤文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下python代码:

Given the following piece of python code:

for root, dirs, files in os.walk(directory):
    for filename in fnmatch.filter(files, '*.png'):
        pass

如何过滤多个扩展名?在这种特殊情况下,我想获取所有以* .png,*.gif,*.jpg或* .jpeg结尾的文件.

How can I filter for more than one extension? In this special case I want to get all files ending with *.png, *.gif, *.jpg or *.jpeg.

现在我想出了

for root, dirs, files in os.walk(directory):
    for extension in ['jpg', 'jpeg', 'gif', 'png']:
        for filename in fnmatch.filter(files, '*.' + extension):
            pass

但是我认为它不是非常优雅和出色.

But I think it is not very elegant and performant.

有人有更好的主意吗?

推荐答案

如果只需要检查扩展名(即没有其他通配符),为什么不简单地使用基本的字符串操作?

If you only need to check extensions (i.e. no further wildcards), why don't you simply use basic string operations?

for root, dirs, files in os.walk(directory):
    for filename in files:
        if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')):
            pass

这篇关于使用fnmatch.filter通过多个可能的文件扩展名过滤文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆