有人可以告诉我为什么下面的代码正在搜索指定路径中的子文件夹.我只想要搜索c:\ Python27中的所有.txt和.log文件.但搜索显示c:\ Python27\Doc中的.txt和.log文件的结果......依此类推.谢谢.
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(".log") 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()
Run Code Online (Sandbox Code Playgroud)
os.walk是递归目录行走 - 它的文档说:
通过从上到下或从下到上遍历树来生成目录树中的文件名.
所以你得到你要求的东西;-)
如果您不需要递归,请os.listdir改用.由于os.walk默认情况下自上而下,你也可以在第一个目录之后切断循环,但这很麻烦.os.listdir很简单:
>>> 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
Run Code Online (Sandbox Code Playgroud)