2011-04-28 64 views
0

有人可以告訴我爲什麼下面的代碼是在指定的路徑中搜索子文件夾。我只想要搜索c:\ Python27中的所有.txt和.log文件。但是,搜索結果顯示了.txt和.log文件在c:\ Python27 \ Doc中......等等等等。謝謝。我定義了一個搜索路徑,但其他文件夾中的文件正在搜索

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() 

回答

5

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