I defined a search path, but files in otrher folders are being searched
Can someone PLEASE tell me why the below code is searching for sub folders in the specified path. I only want all .txt and .log files in c:\Python27 to be searched. But the search is showing results for .txt and .log file in c:\Python27\Doc ... so on and so forth as well. Thanks.
elif searchType =='3':
print "Directory to be searched: c:\Python27 "
print " "
directory = os.path.join("c:\\","Python27")
regex = re.compile(r'3[0-9]\d{10}')
for root,dirname, files in os.walk(directory):
for file in files:
if file.endswith(".l开发者_运维知识库og") or file.endswith(".txt"):
f=open(os.path.join(root,file))
for line in f.readlines():
searchedstr = regex.findall(line)
for word in searchedstr:
print "String found: " + word
print "File: " + os.path.join(root,file)
break
f.close()
os.walk
is recursive directory walking - its documentation says:
Generate the file names in a directory tree by walking the tree either top-down or bottom-up.
So you get what you ask for ;-)
If you don't need recursion, just use os.listdir
instead. Since os.walk
by default walks top-down you could also cut the loop after the first directory, but it's cumbersome. os.listdir
is simple:
>>> for filename in os.listdir(r"c:\python26\\"):
... if filename.endswith('.txt') or filename.endswith('.log'): print filename
...
lxml-wininst.log
MySQL-python-wininst.log
py2exe-wininst.log
PyXML-wininst.log
scons-wininst.log
精彩评论