2011-09-27 59 views
1

以下示例通過目錄「遍歷」,打印所有文件的名稱,並在所有目錄上遞歸調用自身。文件名和路徑故障

import os 
def walk(dir): 
    for name in os.listdir(dir): 
     path = os.path.join(dir,name) 
     if os.path.isfile(path): 
      print path 
     else: 
      walk1(path) 

os.path.join` takes a directory and a file name and joins them into a complete path. 

我練習:修改步行使,而不是打印文件的名稱,它返回名稱的列表。

有人可以解釋這個函數每行做什麼?我有一個好主意,但是當它到達這條線時:else: walk(path),這讓我不知所措,因爲沒有任何解釋。在這個練習中,我能想到這個更改爲列表中的唯一方法是:

def walk1(dir): 
    res = [] 
    for name in os.listdir(dir): 
     path = os.path.join(dir,name) 
     if os.path.isfile(path): 
      res.append(path) 
     else: 
      walk1(path) 
    return res 

我的輸出如此多的輸出線只是區區數去。我做得對嗎?

回答

1

下面是一個帶有小修復遞歸的註釋版本。

def walk1(dir): 
    res = [] 
    # for all entries in the folder, 
    for name in os.listdir(dir): 
     # compute the path relative to `dir` 
     path = os.path.join(dir,name) 
     # include entries recursively. 
     if os.path.isfile(path): 
      # the path points to a file, save it. 
      res.append(path) 
     else: 
      # the path points to a directory, so we need 
      # to fetch the list of entries in there too. 
      res.extend(walk1(path)) 
    # produce all entries at once. 
    return res 
+0

另外,下一個練習將討論_os_中稱爲_walk_的函數,而且我需要然而,閱讀有關這方面的文件;我需要打印給定目錄及其子目錄中文件的名稱。如果我正確解釋這個問題,那麼res.extend也不是那麼簡單嗎? –

1

您需要將遞歸結果添加到您已有的結果中。

+0

我剛剛意識到,步行(路徑)與我在此處定義的函數不同,遞歸不一樣<抱歉......它是walk1() –

1

我寫的一個小模塊pathfinder使我更容易找到路徑(在我看來,無論如何)。

from pathfinder import pathfind 
paths = pathfind(a_dir, just_files=True) 

它只是os.walk上的一層,但是消除了一些圍繞它的困惑。