-1

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

14102 1 1 /home/bob/桌面

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("/"))

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

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

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

这是错误消息。

4

1 回答 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

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


print max([x for x in d ],key=lambda x: x.count("/"))
于 2014-07-01T09:30:05.657 回答