首页 > 解决方案 > Python fnmatch 带括号和逗号

问题描述

我正在浏览一个目录,并尝试(0, 0, 0)使用fnmatch.fnmatch(filename,'*(0, 0, 0)*'). 看起来括号和逗号正在抛弃它,并与(0, 1, 1)我不想要的字符串匹配。

相关的片段是:

for root, dirs, files in os.walk(data_dir):
    for file in files:
        filename = os.path.join(root, file)
        if fnmatch.fnmatch(filename,'*\(0, 0, 0\)*'):
            # do stuff

并且目录包含以下文件:

\c_(0, 0, 0)\data.txt
\c_(0, 05, 05)\data.txt
\c_(0, 05, 1)\data.txt
\c_(0, 1, 0)\data.txt

我的理解是转义括号应该可以解决它,但那里没有运气。解决此问题的最佳方法是什么?

标签: pythonglob

解决方案


files_list=[]

for filename in os.listdir(r'DirPath'):
    if filename.count('(0, 0, 0)'):
        files_list.append(filename)

推荐阅读