How to find files with specific case-insensitive extension names in Python
13,906
Solution 1
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)]
Solution 2
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.
Author by
Pan Ruochen
Happy to discuss about the following topics: C / Shell / Makefile
Updated on June 08, 2022Comments
-
Pan Ruochen almost 2 years
glob.glob()
is case-sensitive.
Is there any simple way to find files with specific case-insensitive extension names in Python.