Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find files with specific case-insensitive extension names in Python [duplicate]

glob.glob() is case-sensitive.
Is there any simple way to find files with specific case-insensitive extension names in Python.

like image 785
Pan Ruochen Avatar asked Mar 27 '13 05:03

Pan Ruochen


2 Answers

The fnmatch module provides more control over pattern matching than the glob module:

>>> import os
>>> from fnmatch import filter
>>> filter(os.listdir('.'), '*.[Pp][Yy]')

You can also use os.listdir() followed by a regular expression match:

>>> import os, re
>>> [filename for filename in os.listdir('.') 
              if re.search(r'\.py$', filename, re.IGNORECASE)]
like image 74
Raymond Hettinger Avatar answered Oct 30 '22 04:10

Raymond Hettinger


This should do the trick:

import os
import glob

def find_case_insensitve(dirname, extensions):
    for filename in glob.glob(dirname):
        base, ext = os.path.splitext(filename)
        if ext.lower() in extensions:
            print filename


find_case_insensitve('/home/anthon/Desktop/*', ['.jpeg', '.png', '.jpg'])

Don't forget to specify the list of extensions in lowercase.

like image 26
Anthon Avatar answered Oct 30 '22 02:10

Anthon