首页 > 解决方案 > Python中区分大小写的文件路径匹配

问题描述

我有一个带有此路径的目录

Al Furjan/Al Furjan 2D 3D/3D/AZIZI tulip/file.jpg

我有另一个 csv 从中创建路径,路径变成这样

Al Furjan/Al Furjan 2D 3D/3D/AZIZI Tulip/file.jpg

我生成的路径有T大写,但实际目录有 t。我如何用 python 解决这个问题,它在搜索路径时忽略了区分大小写。

标签: python-3.xdirectory

解决方案


您可以使用fnmatch, reand的连词os来做到这一点:

import os
import fnmatch
import re

# translate the file name in a pattern
regex = fnmatch.translate('testit/testIT/testIT.txt')

# compile a case insensitive version of your this pattern
rec = re.compile(regex, re.IGNORECASE)

def listallfiles(path):
    for (dirpath, dirnames, filenames) in os.walk(path):
        for f in filenames:
            yield(os.path.relpath(os.path.join(dirpath, f)))

found = [i for i in listallfiles('.') if rec.match(i)] 

print(found)

推荐阅读