[英]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)*')
.我正在遍历一个目录,并尝试使用
fnmatch.fnmatch(filename,'*(0, 0, 0)*')
收集包含字符串(0, 0, 0)
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.看起来括号和逗号正在抛弃它,并匹配像
(0, 1, 1)
这样的字符串,这是我不想要的。
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\\)*
试试这个:
*\\(0,\\ 0,\\ 0\\)*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.