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

后端 未结 8 1815
面向向阳花
面向向阳花 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:27

    This would be a better way, perhaps because you are not calling + repeatedly and using a tuple instead of list.

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

    A tuple is better because you are not going to modify the extension once you have created them. You are just using to iterate over them.

提交回复
热议问题