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

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

    You can use a list comprehension to check if my_file matches any of the file masks defined in patterns:

    import fnmatch
    
    my_file = 'my_precious.txt'
    patterns = ('*.txt', '*.html', '*.mp3')
    
    
    if [pat for pat in patterns if fnmatch.fnmatch(my_file, pat)]:
        print('We have a match!')
    else:
        print('No match')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题