Search code examples
pythonglob

Python fnmatch with parentheses and commas


I'm doing a walk through a dir, and trying to collect files which contain the string (0, 0, 0) using fnmatch.fnmatch(filename,'*(0, 0, 0)*'). It looks like the parentheses and commas are throwing it off, and matching to strings like (0, 1, 1), which I don't want.

The relevant snippet is:

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

and the dirs contain files such as:

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

My understanding is that escaping the parentheses should fix it, but no luck there. What would be the best way to fix this?


Solution

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