Use fnmatch.filter to filter files by more than one possible file extension

后端 未结 8 1811
面向向阳花
面向向阳花 2021-01-31 02:52

Given the following piece of python code:

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


        
8条回答
  •  醉酒成梦
    2021-01-31 03:14

    I think your code is actually fine. If you want to touch every filename only once, define your own filtering function:

    def is_image_file(filename, extensions=['.jpg', '.jpeg', '.gif', '.png']):
        return any(filename.endswith(e) for e in extensions)
    
    for root, dirs, files in os.walk(directory):
        for filename in filter(is_image_file, files):
            pass
    

提交回复
热议问题