开发者

Filenames and paths trouble

The following example "walks" through a directory, prints the names of all the files, and calls itself recursively on 开发者_JS百科all the directories.

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.

My exercise: Modify walk so that instead of printing the names of the files, it returns a list of names.

Can someone explain what this function is doing per line? I have a good idea but when it gets to the line: else: walk(path), that throws me off since there is no explanation what that is doing. For this exercise, the only way I could think to change this to a list is by:

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

My output went from so many output lines to just a mere few. Did I do this correctly?


Here's an annotated version with a small fix to the recursion.

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


You need to add the result of your recursion to what you already have.


A small module I wrote, pathfinder, makes it easier (in my opinion anyway) to find paths.

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

It's just a layer on top of os.walk, but removes some of the confusion surrounding it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜