Python 文件名和路径问题

Python 文件名和路径问题,python,path,filenames,Python,Path,Filenames,下面的示例“遍历”一个目录,打印所有文件的名称,并在所有目录上递归调用自身 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

下面的示例“遍历”一个目录,打印所有文件的名称,并在所有目录上递归调用自身

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.
我的练习:修改walk,使其返回名称列表,而不是打印文件名

有人能解释一下每行函数的作用吗?我有一个好主意,但当它到达以下行时:
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

我的输出从如此多的输出行变成了仅有的几行。我做得对吗?

您需要将递归的结果添加到已有的结果中。

这里是一个带注释的版本,对递归进行了一个小的修复

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
我写的一个小模块使查找路径变得更容易(在我看来)

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

它只是os.walk之上的一个层,但消除了围绕它的一些混乱。

我刚刚意识到,walk(path)与我在这里定义的函数不是同一个递归。。。也是walk1(),下一个练习将讨论操作系统中名为walk的函数,但是我需要阅读有关此函数的文档;我需要打印给定目录及其子目录中的文件名。如果我正确地解释的话,这不也是res.extend吗?