2011-09-27 80 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上的一层,但是消除了一些围绕它的困惑。