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 strin开发者_运维技巧g
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 ?
Try using os.path.splitext
to check for a matching file extension.
for path, subdirs, files in os.walk(path):
for name in files:
if os.path.splitext(name)[1] 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
The rest looks fine.
精彩评论