2011-04-28 46 views
31

我想要瀏覽當前文件夾及其所有子文件夾,並獲取帶有.htm | .html擴展名的所有文件。我發現,這是可以找出一個對象是否是一個目錄或文件是這樣的:在Python中瀏覽文件和子文件夾

import os 

dirList = os.listdir("./") # current directory 
for dir in dirList: 
    if os.path.isdir(dir) == True: 
    # I don't know how to get into this dir and do the same thing here 
    else: 
    # I got file and i can regexp if it is .htm|html 

,並在最後,我想擁有所有的文件和它們在陣列中的路徑。有這樣的可能嗎?

+0

可能重複【如何通過在目錄中的文件遍歷?(http://stackoverflow.com/questions/ 4918458/how-to-tra-through-the-files-in-a-directory) – 2011-04-28 11:12:10

+3

但在這個答案中的答案更短,更好。 – Blackie123 2012-02-25 08:51:50

回答

84

您能給我們os.walk()遞歸通過目錄遍歷及其所有子目錄:

for root, dirs, files in os.walk(path): 
    for name in files: 
     if name.endswith((".html", ".htm")): 
      # whatever 

建立這些名稱的列表,你可以使用列表理解:

htmlfiles = [os.path.join(root, name) 
      for root, dirs, files in os.walk(path) 
      for name in files 
      if name.endswith((".html", ".htm"))] 
2

使用newDirName = os.path.abspath(dir)爲子目錄創建一個完整的目錄路徑名,然後列出其內容,如同完成父級(即newDirList = os.listDir(newDirName)

您可以爲代碼片段創建一個單獨的方法,並通過子目錄結構遞歸調用它。第一個參數是目錄路徑名。這將改變每個子目錄。

此答案基於Python庫的3.1.1版本文檔。 Python 3.1.1 Library Reference(第10章 - 文件和目錄訪問)的第228頁有一個很好的示例。 祝你好運!

-2

的斯文Marnach的解決方案稍加改動版本..


import os

folder_location = 'C:\SomeFolderName' file_list = create_file_list(folder_location)

def create_file_list(path): return_list = []

for filenames in os.walk(path): for file_list in filenames: for file_name in file_list: if file_name.endswith((".txt")): return_list.append(file_name) return return_list

+0

由於某些原因,有額外的空間和for塊的縮進不正確的上述粘貼.. SO的標記不喜歡我.. – campervancoder 2014-01-05 21:17:27

+2

簡單的代碼返工不佳 - 用嵌入循環替換元組賦值使代碼可讀性較差,可能效率更低 – volcano 2014-01-05 21:23:37

+0

感謝評論@ volcano ..上面的例子似乎沒有工作,因此額外的循環.. – campervancoder 2014-01-07 19:48:13

相關問題