python DFS目录并打印出最长的路径

时间:2014-06-30 21:03:56

标签: python directory depth-first-search longest-path

我在这里遇到一些问题。我可以搜索所有目录并打印出来,但我找不到最长的路径。这是我的终端统计数据。

14102 1 1 /家庭/鲍勃/桌面

import os

def DFS(path, dirCallback = None, fileCallback = None):
    stack = []
    ret = []
    stack.append(path);
    while len(stack) > 0:
        tmp = stack.pop(len(stack) - 1)
        if(os.path.isdir(tmp)):
            ret.append(tmp)
            for item in os.listdir(tmp):
                stack.append(os.path.join(tmp, item))
            if dirCallback:
                dirCallback(tmp)
        elif(os.path.isfile(tmp)):
            ret.append(tmp)
            if fileCallback:
                fileCallback(tmp)
    return ret

def print_directory(path):
    print "dir: " + path

def print_file(path):
    print "file: " + path

d = DFS('~/', print_directory, print_file)

print max([x for x in d ],key=lambda x: x.count("/"))

我只是不知道为什么它不能打印出这里最长的路径。我只是蟒蛇的新手,我也是英语学习者,如果我有任何误解,请告诉我。

更新:我现在可以找到最长的路径,但我不能使用'〜/'找到目录。

Traceback (most recent call last):
  File "Search.py", line 29, in <module>
    print max([x for x in d ],key=lambda x: x.count("/"))
ValueError: max() arg is an empty sequence

这是错误信息。

1 个答案:

答案 0 :(得分:1)

此代码应完全正常运行:

import os

def DFS(path, dirCallback = None, fileCallback = None):
    stack = []
    ret = []
    stack.append(path);
    while len(stack) > 0:
        tmp = stack.pop(len(stack) - 1)
        if(os.path.isdir(tmp)):
            ret.append(tmp)
            for item in os.listdir(tmp):
                stack.append(os.path.join(tmp, item))
            if dirCallback:
                dirCallback(tmp)
        elif(os.path.isfile(tmp)):
            ret.append(tmp)
            if fileCallback:
                fileCallback(tmp)
    return ret

def print_directory(path):
    print "dir: " + path

def print_file(path):
    print "file: " + path

home = os.path.expanduser('~')
d = DFS(home, print_directory, print_file)


print max([x for x in d ],key=lambda x: x.count("/"))