简体   繁体   中英

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?

files_list=[]

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

you need to escape spaces also.

try this : *\\(0,\\ 0,\\ 0\\)*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM