2017-04-04 85 views
0

你好,我想知道一個路徑是否存在於一個目錄遞歸。 我寫了一個腳本,但速度太慢。 所以我想知道還有其他的方法。 「路徑」是完整路徑的部分字符串。如何用python遞歸搜索路徑是否存在於目錄中?

bMatch = False 
    for dirpath, dirnames, filenames in os.walk("."): 
     for f in filenames : 
      full_path = os.path.join(dirpath, f) 
      logger.error(full_path) 
      if path in full_path : 
       bMatch = True 
       logger.error("Matched") 
       break 
     if bMatch == True : 
      break 
    if bMatch == False : 
     logger.error("[Error] Path doesn't exist. Please check " + path + ' in the row ' + str(row + 1)) 
+1

什麼是你使用的軟件包,變量'path'來自哪裏...請閱讀[如何創建一個最小,完整和可驗證的例子](http://stackoverflow.com/help/mcve ) – Kanak

+0

當你說「路徑是部分字符串」,你的意思是它是一些父文件夾或例如'c:\ ag'作爲'c:\ agnes'的部分字符串? – asongtoruin

回答

0

您可以使用os.listdir和運算存儲到queue。然後,你可以驗證路徑。請參閱我的toy project以瞭解如何過濾隱藏以及可見的目錄和文件。您將獲得有關處理文件和目錄的基本想法。