python处理匹配的完整列表文件
我正在尝试让简单的代码工作,不幸的是我是一个Python初学者。
我的脚本应该返回与模式不匹配的文件列表,更多信息如下: python grep 反向匹配
我的代码正在运行,但未处理完整列表找到的文件数量:
import sys,os
filefilter = ['.xml','java','.jsp','lass']
path= "/home/patate/code/project"
s = "helloworld"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
f = str(os.path.join(path, name))
with open(f) as fp:
if s in fp.read():
print "%s has the string" % f
else:
print "%s doesn't have the string" % f
此代码返回:
/home/patate/code/project/blabla/blabla/build.xml 没有字符串
无
如果我将 f = str(os.path.join(path, name)) 更改为 print str(os. path.join(路径, 名称))
我可以看到整个列表正在打印。
我怎样才能按照我的意愿处理整个列表?
I'm trying to get simple code working, unfortunately I'm a python beginner.
My script should return a list of files that doesn't match a pattern, more information here :
python grep reverse matching
My code is running but doesn't process the complete list of files found as it should :
import sys,os
filefilter = ['.xml','java','.jsp','lass']
path= "/home/patate/code/project"
s = "helloworld"
for path, subdirs, files in os.walk(path):
for name in files:
if name[-4:] in filefilter :
f = str(os.path.join(path, name))
with open(f) as fp:
if s in fp.read():
print "%s has the string" % f
else:
print "%s doesn't have the string" % f
This code returns :
/home/patate/code/project/blabla/blabla/build.xml doesn't have the string
None
If I change f = str(os.path.join(path, name)) for print str(os.path.join(path, name))
I can see the whole list being printed.
How can I process the whole list as I wish to ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试使用 os.path.splitext 检查匹配的文件扩展名。
其余的看起来都不错。
Try using
os.path.splitext
to check for a matching file extension.The rest looks fine.