如何在Python中查找具有特定于大小写不敏感的扩展名的文件[重复]

时间:2022-12-26 10:36:40

This question already has an answer here:

这个问题在这里已有答案:

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

glob.glob()区分大小写。有没有简单的方法可以在Python中查找具有特定于大小写不敏感的扩展名的文件。

2 个解决方案

#1


10  

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

与glob模块相比,fnmatch模块提供了对模式匹配的更多控制:

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

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

您还可以使用os.listdir(),然后使用正则表达式匹配:

>>> import os, re
>>> [filename for filename in os.listdir('.') 
              if re.search(r'\.py$', filename, re.IGNORECASE)]

#2


5  

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.

不要忘记以小写形式指定扩展名列表。

#1


10  

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

与glob模块相比,fnmatch模块提供了对模式匹配的更多控制:

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

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

您还可以使用os.listdir(),然后使用正则表达式匹配:

>>> import os, re
>>> [filename for filename in os.listdir('.') 
              if re.search(r'\.py$', filename, re.IGNORECASE)]

#2


5  

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.

不要忘记以小写形式指定扩展名列表。